Ubuntu bash script: how to split path by last slash?

前端 未结 4 1517
忘掉有多难
忘掉有多难 2020-12-12 22:17

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/ba         


        
4条回答
  •  萌比男神i
    2020-12-12 23:12

    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.

提交回复
热议问题