簡體   English   中英

如何從命令輸出中獲取第二列?

[英]How to get the second column from command output?

我的命令輸出類似於:

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

第一列始終是數字,后跟空格,然后是雙引號字符串。

我的目的是僅獲得第二列,例如:

"A B"
"C"
"D"

我打算使用<some_command> | awk '{print $2}' <some_command> | awk '{print $2}'來實現這一目標。 但問題是,第二列中的某些值包含空格,這恰好是awk分隔字段的默認分隔符。 因此,輸出搞砸了:

"A
"C"
"D"

如何干凈地獲得第二列的值(帶配對的引號)?

使用-F [field separator]分割" s: "的行

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

或來自管道的輸入

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

輸出:

A B
C
D

如果您可以使用“awk”以外的其他內容,請嘗試使用此功能

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

-d是分隔符, -f是要切割的字段,使用-f2-我們打算將第2個字段切割到結束。

這應該可以從命令輸出“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

這將打印第三列

或者使用sed和regex。

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

你不需要awk。 在Bash shell中使用read應該足夠了,例如

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

要么:

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

如果你有GNU awk這就是你想要的解決方案:

$ awk '{print $1}' FPAT='"[^"]+"' file
"A B"
"C"
"D"
awk -F"|" '{gsub(/\"/,"|");print "\""$2"\""}' your_file
#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM