我的命令输出如下:

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

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

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

"A B"
"C"
"D"

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

"A
"C"
"D"

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


当前回答

或者使用sed和regex。

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

其他回答

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

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

或者从管道输入

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

输出:

A B
C
D
awk -F"|" '{gsub(/\"/,"|");print "\""$2"\""}' your_file

或者使用sed和regex。

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

你不需要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

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

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