简体   繁体   中英

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:

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.

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 '{ 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?

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

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}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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