Search code examples
shellunixawkcut

get the file name from the path


I have a file file.txt having the following structure:-

./a/b/c/sdsd.c
./sdf/sdf/wer/saf/poi.c
./asd/wer/asdf/kljl.c
./wer/asdfo/wer/asf/asdf/hj.c

How can I get only the c file names from the path. i.e., my output will be

sdsd.c
poi.c
kljl.c
hj.c

Solution

  • You can do this simpy with using awk.

    set field seperator FS="/" and $NF will print the last field of every record.

    awk 'BEGIN{FS="/"} {print $NF}' file.txt
    

    or

    awk -F/ '{print $NF}' file.txt
    

    Or, you can do with cut and unix command rev like this

    rev file.txt | cut -d '/' -f1 | rev