I want to use AWK to get the filename or the last folders name if the string is only a directory.

I have:

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

to print the last column and:

 awk -F '/' '{print $(NF - 1)}

to print one column before the last.

How can I make awk recognize if the string contains only a directory and no filename and in this case print one column before the last.

My problem is that a directory might look like:


and in this case the last column would be empty. I want awk to recognize this and then print folder3 (so one column before the last one).


You can either use if or the ?: operator for this.

awk -F '/' '{print $NF == "" ? $(NF - 1) : $NF}'
awk -F '/' '{if($NF == "") print $(NF - 1); else print $NF}'
  • 1
    ternary operand test ? true : false is a clever choice. – Archemar Dec 6 '18 at 19:01

With GNU utilities see also:

xargs -rd '\n' basename -a --

Which on a list.txt input like:




zsh's :t modifier (from csh) gives "" for "/" instead of "/"

$ printf '<%s>\n' "${(@)${(f)$(<list.txt)}:t}"


awk -F/ '{if (length($NF)) print $NF ; else print $(NF-1) ;}' 

(I wasn't able to test it though).


In the shell:

$ basename ./folder1/folder2/folder3/

Assigning to a variable, using basename with a variable that holds a pathname:

filename=$( basename "$pathname" )

The basename utility is a standard POSIX utility.

  • thx, my question has been gaining a bit much on the use of AWK, using basename is much simpler. – nath Jan 28 '19 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.