I have this file as input:

root      1243  0.0  0.0  65508  6036 ?        Ss   Apr30   0:05 /usr/sbin/sshd -D
root      7385  0.0  0.1 152932 10644 ?        Ss   16:22   0:00 sshd: per1 [priv]
per2  7425  0.0  0.0 152932  6216 ?        S    16:22   0:00 sshd: per2@pts/7
root      8256  0.0  0.1 152876 10240 ?        Ss   16:32   0:00 sshd: per3 [priv]
per3  8298  0.0  0.0 152876  5308 ?        S    16:32   0:00 sshd: per3@pts/9

I want to be able to select the first column of unique names:

cut -f 1 file.txt | sort | uniq but this will not work. I have to do cut -f 1 -d " " file.txt ...

Why do I add in this -d 1? It is my understanding that when the spaces between the columns are not tabs, we must write what it is. In this case it is " ", so thats why we write it. Is this correct?

Then how do I select the 2nd column here? I simply changed the cut -f 1 to cut -f 2 but this did not do it. My output for that was a bunch of empty lines? Why? Why did it work for cut -f 1 but not 2?

  • So are you saying that if the distance between the first and second column was only one space, then it would work?
    – K Split X
    May 16 '18 at 0:36

If you want the first space-separated field with cut, then you have to tell it to use spaces instead of the default of TABs:


-d, --delimiter=DELIM

use DELIM instead of TAB for field delimiter

As soon as you tell cut to use spaces as the delimiter, that's what it uses, and so "field 2" becomes the first byte(s) following the first space (until it sees another delimiter); in your case, that's a space.

Use this data as an illustrative example:

root 1space 2space 3space

... where there's one space before 1space, two before 2space and three before 3space.

$ seq 1 7 | while read index; do echo "$index" - "$(cut -d' ' -f $index < input)"; done
1 - root
2 - 1space
3 -
4 - 2space
5 -
6 -
7 - 3space

Since you have a variable number of spaces separating the fields in the input, I'd suggest:

  • If you're OK "changing" the data, use sed to reduce multiple spaces to one, as steeldriver showed: sed 's/ */ /g' < input | cut -d' ' -f2.
  • Otherwise, consider a tool like awk that splits fields on multiple subsequent field separators: awk '{print $2}' < input
  • Regarding your first sentence, I don't see how the first field is separated by spaces? It is the first field. The second field I can surely say is separated by spaces on both sides.
    – K Split X
    May 16 '18 at 10:21
  • The first field ends at the first space (delimiter).
    – Jeff Schaller
    May 16 '18 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.