Grep – Why Doesn’t cut -d ‘ ‘ Work with Space?

cutgrep

I've no issue with this cut command.

wolf@linux:~$ echo ab cd ef
ab cd ef

wolf@linux:~$ echo ab cd ef | cut -d ' ' -f 1
ab

wolf@linux:~$ echo ab cd ef | cut -d ' ' -f 2
cd

However, when I try the same command with different input like this, I did not get the output as expected.

wolf@linux:~$ ip address show eth0 | grep 'inet '
    inet 10.10.10.10/24 brd 10.10.10.255 scope global dynamic eth0

wolf@linux:~$ ip address show eth0 | grep 'inet ' | cut -d ' ' -f 1

wolf@linux:~$ ip address show eth0 | grep 'inet ' | cut -d ' ' -f 2

What's wrong in the second example?

awk doesn't seems to have a problem with the same input, strange.

wolf@linux:~$ ip address show eth0 | awk '/inet / {print $1}'
inet

wolf@linux:~$ ip address show eth0 | awk '/inet / {print $2}'
10.10.10.10/24

Best Answer

cut takes each and every delimiter as meaningful, even if there are consecutive spaces. This is unlike awk, which by default splits on whitespace, but takes multiple whitespace as only one delimiter, and ignore leading whitespace.

You could get awk to behave similarly by setting the field separator FS to [ ]:

$ ip add show lo | awk -F'[ ]' '$5 == "inet" {print $6}'
127.0.0.1/8

That has to be set like that, as a regexp, since a single space by itself in FS marks the default, special operation.

See, e.g. the GNU awk manual has to say on field separators.

Related Question