How to split path by last slash?

BashSplit

Bash Problem Overview


I have a file (say called list.txt) that contains relative paths to files, one path per line, i.e. something like this:

foo/bar/file1
foo/bar/baz/file2
goo/file3

I need to write a bash script that processes one path at a time, splits it at the last slash and then launches another process feeding it the two pieces of the path as arguments. So far I have only the looping part:

for p in `cat list.txt`
do
   # split $p like "foo/bar/file1" into "foo/bar/" as part1 and "file1" as part2
   inner_process.sh $part1 $part2
done

How do I split? Will this work in the degenerate case where the path has no slashes?

Bash Solutions


Solution 1 - Bash

Use basename and dirname, that's all you need.

part1=$(dirname "$p")
part2=$(basename "$p")

Solution 2 - Bash

A proper 100% bash way and which is safe regarding filenames that have spaces or funny symbols (provided inner_process.sh handles them correctly, but that's another story):

while read -r p; do
    [[ "$p" == */* ]] || p="./$p"
    inner_process.sh "${p%/*}" "${p##*/}"
done < list.txt

and it doesn't fork dirname and basename (in subshells) for each file.

The line [[ "$p" == */* ]] || p="./$p" is here just in case $p doesn't contain any slash, then it prepends ./ to it.

See the Shell Parameter Expansion section in the Bash Reference Manual for more info on the % and ## symbols.

Solution 3 - Bash

I found a great solution from this source.

p=/foo/bar/file1
path=$( echo ${p%/*} )
file=$( echo ${p##*/} )

This also works with spaces in the path!

Solution 4 - Bash

Here is one example to find and replace file extensions to xml.

for files in $(ls); do

    filelist=$(echo $files |cut -f 1 -d ".");
    mv $files $filelist.xml;
done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionI ZView Question on Stackoverflow
Solution 1 - BashpiokucView Answer on Stackoverflow
Solution 2 - Bashgniourf_gniourfView Answer on Stackoverflow
Solution 3 - BashphroggView Answer on Stackoverflow
Solution 4 - BashSanjeeb MohantaView Answer on Stackoverflow