6

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:

./folder1/folder2/folder3/

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).

4 Answers 4

10

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
  • 1
    ternary operand test ? true : false is a clever choice.
    – Archemar
    Commented Dec 6, 2018 at 19:01
3

try

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

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

0
3

With GNU utilities see also:

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

Which on a list.txt input like:

./folder1/folder2/folder3/
./foo
bar///
/

gives:

folder3
foo
bar
/

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

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

In the shell:

$ basename ./folder1/folder2/folder3/
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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .