简体   繁体   English

我如何打印特定字段,并从每行包含分隔符的最后一个字段中获取最后一个单词

[英]How can i print specific fields, and get last word from last field that contain delimiter in each line

This maybe simple, but with lack of my programming skill, i can't figure it how to accomplish this.这可能很简单,但是由于缺乏我的编程技能,我无法弄清楚如何实现这一点。

I have content of file.txt like this:我有这样的file.txt内容:

1 22 July 2003 Path /Documents/Photo
2 23 July 2003 Path /Documents/Photo
3 24 July 2003 Path /Documents/Photo

and i only want to print field 2,3,4 and last word from last field that contain separator '/' each line.我只想打印字段 2,3,4 和最后一个字段的最后一个单词,每行包含分隔符“/”。

like this:像这样:

22 July 2003 Photo
23 July 2003 Photo
24 July 2003 Photo

i've tried this with awk command, but its delete all word from last field.我已经用 awk 命令尝试了这个,但是它从最后一个字段中删除了所有单词。

awk '{ print $2,$3,$4,$(NF=$NF) }'

Lynx:~ root# cat file.txt | awk '{ print $2,$3,$4,$(NF=$NF) }'
22 July 2003
23 July 2003
24 July 2003

how can i accomplish this with awk,sed or grep?我如何使用 awk、sed 或 grep 来完成此操作?

Thanks in Advance!提前致谢!

You can split the last field on / and get the last item from the array您可以在/上拆分最后一个字段并从数组中获取最后一项

awk '{ 
i = split($NF,a,"/")
print $2,$3,$4,a[i] 
}' file

Output Output

22 July 2003 Photo
23 July 2003 Photo
24 July 2003 Photo

You could also remove all until the last occurence of / in the last field.您也可以在最后一个字段中最后一次出现/之前删除所有内容。

awk '{ 
sub(/.*\//, "", $NF)
print $2,$3,$4,$NF
}' file

With your shown samples, please try following.使用您显示的示例,请尝试以下操作。 Simply setting field separator to space OR / here and printing 2nd, 3rd, 4th and last field's values for each lines.只需在此处将字段分隔符设置为空格或 / 并为每行打印第二、第三、第四和最后一个字段的值。

awk -F'[ /]' '{print $2,$3,$4,$NF}' Input_file

another one另一个

$ awk '{print $2,$3,$4,a[split($NF,a,"/")]}' file

or或者

$ awk '{sub(/.*\//,"",$NF); print $2,$3,$4,$NF}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM