我对这个cut命令没有异议。
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但是,当我尝试使用这样的不同输入的相同命令时,我没有得到预期的输出。
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第二个例子有什么问题?
奇怪的是,awk在相同的输入上似乎没有问题。
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发布于 2020-08-27 14:37:07
cut将每一个分隔符都视为有意义的,即使有连续的空格。这与awk不同,后者默认在空格上拆分,但只使用多个空格作为分隔符,而忽略前面的空格。
通过将字段分隔符FS设置为[ ],可以使awk的行为类似:
$ ip add show lo | awk -F'[ ]' '$5 == "inet" {print $6}'
127.0.0.1/8必须将其设置为regexp,因为FS中的单个空格标志着默认的特殊操作。
例如,GNU手册必须说是关于场分离器。
发布于 2020-08-27 14:26:36
输出中的grep行以4个空格开头,如果选择第五个字段,将得到第一个字符串:
admin:~ # ip address show eth0 | grep 'inet ' | cut -d " " -f 5
inethttps://unix.stackexchange.com/questions/606639
复制相似问题