Reputation: 41
I have a file containing multiple full path
/home/pi/1.txt
/home/pi/2.txt
/home/pi/3.txt
and I want to get the basename of every file
1.txt
2.txt
3.txt
I only know that I can get the every line and use command
basename
Is it possible to achive my goal more simple? Thank you.
Upvotes: 0
Views: 399
Reputation: 37404
Another in awk:
$ awk 'sub(/.*\//,"")||1' file
1.txt
2.txt
3.txt
Upvotes: 2
Reputation: 133458
@try:
awk -F"/" '{print $NF}' Input_file
Making "/" as field separator and printing the last field of each line.
Upvotes: 1
Reputation:
A solution that use only shell tools:
readarray -t arr <file.txt
echo "${arr[@]##*/}"
This assumes that each file is one line (even with spaces). Filenames with newlines will fail as some other structure would be needed in the file.
Upvotes: 1
Reputation: 1760
The simplest way I came up with is this:
basename -a $(<foo.txt)
Which works because the process substitution $()
is the redirected output of the file, which is then split into multiple arguments because of word-splitting. Basename takes multiple args with -a
.
Note that this doesn't work if there are spaces in the pathnames in the file (because of the said wordsplitting).
Upvotes: 2