Get file name from path

I have a file.txt file 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 file names c from the path. that is, my conclusion will be

 sdsd.c poi.c kljl.c hj.c 
+4
source share
5 answers

You can do this simpy with awk.

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

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

or

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

Or you can do it with the cut command and unix rev

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

+4
source

You can use the basename command:

 basename /a/b/c/sdsd.c 

will provide you sdsd.c

For a list of files in file.txt this will do:

 while IFS= read -r line; do basename "$line"; done < file.txt 
+4
source

The easiest ( $NF is the last column of the current row):

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

or using and a parameter extension :

 while read file; do echo "${file##*/}"; done < file.txt 

or bash using basename :

 while read file; do basename "$file"; done < file.txt 

OUTPUT

 sdsd.c poi.c kljl.c hj.c 
+1
source

Perl Solution:

 perl -F/ -ane 'print $F[@F-1]' your_file 

You can also use sed:

 sed 's/.*[/]//g' your_file 
+1
source

Using sed :

 $ sed 's|.*/||g' file sdsd.c poi.c kljl.c hj.c 
+1
source

Source: https://habr.com/ru/post/1447189/


All Articles