Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last field using awk substr

Tags:

unix

substr

awk

People also ask

How do you get the last line in awk?

Find out the last line of a file: Using sed (stream editor): sed -n '$p' fileName. Using tail: tail -1 fileName. using awk: awk 'END { print }' fileName.

How do I use substr in awk?

substr(str, start, l) This function returns the substring of string str, starting at index start of length l. If length is omitted, the suffix of str starting at index start is returned.

How do you remove the last field in awk?

$NF stores the last column by default, in awk. Here is the command to delete last column of ls -l command's output. In this case, we specify awk command to output all fields where NF contains the number of fields in the input. We subtract 1 from it, to prevent the last field from being counted & printed.


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

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

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

If you're open to a Perl solution, here one similar to fedorqui's awk solution:

perl -F/ -lane 'print $F[-1]' input

-F/ specifies / as the field separator
$F[-1] is the last element in the @F autosplit array


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