Get last field using awk substr Get last field using awk substr unix unix

Get last field using awk substr


Use the fact that awk splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to / you can say:

awk -F "/" '{print $NF}' input

as NF refers to the number of fields of the current record, printing $NF means printing the last one.

So given a file like this:

/home/parent/child1/child2/child3/filename/home/parent/child1/child2/filename/home/parent/child1/filename

This would be the output:

$ awk -F"/" '{print $NF}' filefilenamefilenamefilename


In this case it is better to use basename instead of awk:

 $ basename /home/parent/child1/child2/filename filename


Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"$ echo ${foo##*/}filename$ foo="/home/parent/child/child2/filename"$ echo ${foo##*/}filename