alankrita
alankrita

Reputation: 91

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

Upvotes: 4

Views: 249

Answers (5)

Vijay
Vijay

Reputation: 67221

Perl solution:

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

Also you can use sed:

sed 's/.*[/]//g' your_file

Upvotes: 1

P.P
P.P

Reputation: 121387

You can use basename command:

basename /a/b/c/sdsd.c

will give 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

Upvotes: 4

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185053

The most simple one ($NF is the last column of current line):

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

or using & parameter expansion:

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

or bash with basename :

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

OUTPUT

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

Upvotes: 1

avinashse
avinashse

Reputation: 1460

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

Upvotes: 4

dogbane
dogbane

Reputation: 274592

Using sed:

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

Upvotes: 1

Related Questions