Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete everything before last / in a file path

Tags:

bash

filepath

I have many file paths in a file that look like so:

/home/rtz11/files/testfiles/547/prob547455_01

I want to use a bash script that will print all the filenames to the screen, basically whatever comes after the last /. I don't want to assume that it would always be the same length because it might not be.

Would there be a way to delete everything before the last /? Maybe a sed command?

like image 326
Sal Avatar asked Apr 21 '15 01:04

Sal


3 Answers

Using sed for this is vast overkill -- bash has extensive string manipulation built in, and using this built-in support is far more efficient when operating on only a single line.

s=/home/rtz11/files/testfiles/547/prob547455_01
basename="${s##*/}"
echo "$basename"

This will remove everything from the beginning of the string greedily matching */. See the bash-hackers wiki entry for parameter expansion.


If you only want to remove everything prior to the last /, but not including it (a literal reading of your question, but also a generally less useful operation), you might instead want if [[ $s = */* ]]; then echo "/${s##*/}"; else echo "$s"; fi.

like image 188
Charles Duffy Avatar answered Nov 16 '22 03:11

Charles Duffy


awk '{print $NF}' FS=/ input-file

The 'print $NF' directs awk to print the last field of each line, and assigning FS=/ makes forward slash the field delimeter. In sed, you could do:

sed 's@.*/@@' input-file

which simply deletes everything up to and including the last /.

like image 29
William Pursell Avatar answered Nov 16 '22 02:11

William Pursell


Meandering but simply because I can remember the syntax I use:

cat file | rev | cut -d/ -f1 | rev

Many ways to skin a 'cat'. Ouch.

like image 22
unifex Avatar answered Nov 16 '22 02:11

unifex