[英]How to get the second column from command output?
My command's output is something like: 我的命令输出类似于:
1540 "A B"
6 "C"
119 "D"
The first column is always a number, followed by a space, then a double-quoted string. 第一列始终是数字,后跟空格,然后是双引号字符串。
My purpose is to get the second column only, like: 我的目的是仅获得第二列,例如:
"A B"
"C"
"D"
I intended to use <some_command> | awk '{print $2}'
我打算使用
<some_command> | awk '{print $2}'
<some_command> | awk '{print $2}'
to accomplish this. <some_command> | awk '{print $2}'
来实现这一目标。 But the question is, some values in the second column contain space(s), which happens to be the default delimiter for awk
to separate the fields. 但问题是,第二列中的某些值包含空格,这恰好是
awk
分隔字段的默认分隔符。 Therefore, the output is messed up: 因此,输出搞砸了:
"A
"C"
"D"
How do I get the second column's value (with paired quotes) cleanly? 如何干净地获得第二列的值(带配对的引号)?
Use -F [field separator]
to split the lines on "
s: 使用
-F [field separator]
分割"
s: "
的行
awk -F '"' '{print $2}' your_input_file
or for input from pipe 或来自管道的输入
<some_command> | awk -F '"' '{print $2}'
output: 输出:
A B
C
D
If you could use something other than 'awk' , then try this instead 如果您可以使用“awk”以外的其他内容,请尝试使用此功能
echo '1540 "A B"' | cut -d' ' -f2-
-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end. -d是分隔符, -f是要切割的字段,使用-f2-我们打算将第2个字段切割到结束。
This should work to get a specific column out of the command output "docker images": 这应该可以从命令输出“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
This is going to print the third column 这将打印第三列
或者使用sed和regex。
<some_command> | sed 's/^.* \(".*"$\)/\1/'
You don't need awk for that. 你不需要awk。 Using
read
in Bash shell should be enough, eg 在Bash shell中使用
read
应该足够了,例如
some_command | while read c1 c2; do echo $c2; done
or: 要么:
while read c1 c2; do echo $c2; done < in.txt
If you have GNU awk this is the solution you want: 如果你有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
Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :- 然后,假设您将脚本命名为co,比如说,执行类似这样的操作来获取文件的大小(该示例假定您使用的是Linux,但脚本本身与操作系统无关): -
ls -lh | co 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.