我连续运行两个awk
命令,根据多个分隔符分解字符串。我想知道它们是否可以组合成一个命令。
输入数据(jot -w "some string, this is number " 10
):
some string, this is number 1
some string, this is number 2
some string, this is number 3
some string, this is number 4
some string, this is number 5
some string, this is number 6
some string, this is number 7
some string, this is number 8
some string, this is number 9
some string, this is number 10
这只是示例数据,但我希望能够先根据逗号分割字符串,然后从第二部分中提取数字(第四个字)。实际上,字符串第一部分中的空格数可能会有所不同,即以下是有效输入:
some string, this is number 1
some string with more spaces, this is number 2
以下命令正常工作:
$ jot -w "some string, this is number " 10 | awk -F ',' '{print $2}' | awk -F ' ' '{print $4}'
1
2
3
4
5
6
7
8
9
10
有没有简单的方法将这两个命令合并为一个?
答案 0 :(得分:3)
split()
功能可以让你这样做:
awk '{split($0,a,",");split(a[2],b," ");print b[4];}'
答案 1 :(得分:2)
您可以使用NF轻松打印最后一列
jot -w "some string, this is number " 10 |awk '{print $NF}'
或者按照你的想法,将两个awk合并为一个。
jot -w "some string, this is number " 10 |awk '{l=split($2,a,OFS);print a[l]}' FS=","
答案 2 :(得分:1)
要解决您描述的问题:
$ cat file
some string, this is number 1
some string with more spaces, this is number 2
$ awk -F, '{n=split($NF,a,/ /); print a[n]}' file
1
2
或者如果你喜欢高尔夫:
$ awk -F, '{print a[split($NF,a,/ /)]}' file
1
2
但很明显,您指定的输入会起作用:
$ awk '{print $NF}' file
1
2
以及其他各种解决方案。