我的命令输出如下:

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

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

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

"A B"
"C"
"D"

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

"A
"C"
"D"

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


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

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

或者从管道输入

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

输出:

A B
C
D

或者使用sed和regex。

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

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

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

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

如果你可以使用'awk'以外的东西,那么试试这个

echo '1540 "A B"' | cut -d' ' -f2-

-d是分隔符,-f是要切割的字段,使用-f2-我们打算切割第二个字段直到结束。


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

这应该可以从命令输出"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

这将输出第三列


#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

然后,假设你将脚本命名为co,比如说,做一些类似这样的事情来获取文件的大小(这个例子假设你使用的是Linux,但是脚本本身是独立于操作系统的):-

ls -lh | co 5