Search code examples
linuxunixsunos

Unix command to remove everything after first column


I have a text file in which I have something like this-

10.2.57.44      56538154    3028
120.149.20.197  28909678    3166
10.90.158.161   869126135   6025

In that text file, I have around 1,000,000 rows exactly as above. I am working in SunOS environment. I needed a way to remove everything from that text file leaving only IP Address (first column in the above text file is IP Address). So after running some unix command, file should look like something below.

10.2.57.44
120.149.20.197
10.90.158.161

Can anyone please help me out with some Unix command that can remove all the thing leaving only IP Address (first column) and save it back to some file again.

So output should be something like this in some file-

10.2.57.44
120.149.20.197
10.90.158.161

Solution

  •  nawk '{print $1}' file > newFile && mv newFile file
    

    OR

     cut -f1 file > newFile && mv newFile file
    

    As you're using SunOS, you'll want to get familiar with nawk (not awk, which is the old, and cranky version of awk, while nawk= new awk ;-).

    In either case, you're printing the first field in the file to newFile.

    (n)awk is a complete programming language designed for the easy manipulation of text files. The $1 means the first field on each line, $9 would mean the ninth field, etc, while $0 means the whole line. You can tell (n)awk what to use to separate the fields by, it might be a tab char, or a '|' char, or multiple spaces. By default, all versions of awk uses white space, i.e. multiple spaces, or 1 tab to delimit the columns/fields, per line in a file.

    For a very good intro to awk, see Grymoire's Awk page

    The && means, execute the next command only if the previous command finished without a problem. This way you don't accidentally erase your good data file, becuase of some error.

    IHTH