Get Last Field with awk
awk with $NF
New Help at Unix Tutorial feature (right bottom of every page) I launched over the weekend is great! Even a few hours I’m online each moring and each evening are giving me plenty of opportunities to meet visitors and to help with Unix questions. Today I discussed awk fields delimiter with someone, speicifcally the part of showing the last field in a string.
NF Variable in awk
Awk has a number of built-in variables. NF is one of them – it shows the total number of https://www.unixtutorial.org/awk-field-separatorfields in a given string that awk just finished parsing. Used with the $ macro, NF becomes $NF and gives you the awk field number NF – which is the last field in an awk string.
If we have a DIRNAME variable with a typical full path, like this:
… then it’s possible to get the name of the last subdirectory in DIRNAME using awk and $NF:
That’s it – as simple as that!
See Also
awk with $NF
New Help at Unix Tutorial feature (right bottom of every page) I launched over the weekend is great! Even a few hours I’m online each moring and each evening are giving me plenty of opportunities to meet visitors and to help with Unix questions. Today I discussed awk fields delimiter with someone, speicifcally the part of showing the last field in a string.
NF Variable in awk Awk has a number of built-in variables. NF is one of them – it shows the total number of https://www.unixtutorial.org/awk-field-separatorfields in a given string that awk just finished parsing. Used with the $ macro, NF becomes $NF and gives you the awk field number NF – which is the last field in an awk string.
If we have a DIRNAME variable with a typical full path, like this:
… then it’s possible to get the name of the last subdirectory in DIRNAME using awk and $NF:
That’s it – as simple as that!