Get last field using awk substr

Mari picture Mari · Jul 29, 2013 · Viewed 154.2k times · Source

I am trying to use awk to get the name of a file given the absolute path to the file.
For example, when given the input path /home/parent/child/filename I would like to get filename I have tried:

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

which works perfectly.
However, I am hard coding $5 which would be incorrect if my input has the following structure:

/home/parent/child1/child2/filename

So a generic solution requires always taking the last field (which will be the filename).

Is there a simple way to do this with the awk substr function?

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Jul 29, 2013

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