我的命令输出如下:

1540 "A B"
   6 "C"
 119 "D"

第一列总是一个数字,后面跟着一个空格,然后是一个双引号字符串。

我的目的是只得到第二列,比如:

"A B"
"C"
"D"

我打算使用<some_command> | awk '{print $2}'来完成这一点。但问题是,第二列中的一些值包含空格,这恰好是awk用于分隔字段的默认分隔符。因此,输出是混乱的:

"A
"C"
"D"

我如何得到第二列的值(成对引号)干净?


当前回答

如果你有GNU awk,这是你想要的解决方案:

$ awk '{print $1}' FPAT='"[^"]+"' file
"A B"
"C"
"D"

其他回答

或者使用sed和regex。

<some_command> | sed 's/^.* \(".*"$\)/\1/'

如果你有GNU awk,这是你想要的解决方案:

$ awk '{print $1}' FPAT='"[^"]+"' file
"A B"
"C"
"D"

使用-F[字段分隔符]分隔s上的行:

awk -F '"' '{print $2}' your_input_file

或者从管道输入

<some_command> | awk -F '"' '{print $2}'

输出:

A B
C
D

这应该可以从命令输出"docker images"中获得一个特定的列:

REPOSITORY                          TAG                 IMAGE ID            CREATED             SIZE
ubuntu                              16.04               12543ced0f6f        10 months ago       122 MB
ubuntu                              latest              12543ced0f6f        10 months ago       122 MB
selenium/standalone-firefox-debug   2.53.0              9f3bab6e046f        12 months ago       613 MB
selenium/node-firefox-debug         2.53.0              d82f2ab74db7        12 months ago       613 MB


docker images | awk '{print $3}'

IMAGE
12543ced0f6f
12543ced0f6f
9f3bab6e046f
d82f2ab74db7

这将输出第三列

你不需要awk。在Bash shell中使用read应该足够了,例如。

some_command | while read c1 c2; do echo $c2; done

or:

while read c1 c2; do echo $c2; done < in.txt