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

前端 未结 4 1503
忘掉有多难
忘掉有多难 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条回答
  • 2020-12-12 22:59

    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
    
    0 讨论(0)
  • 2020-12-12 23:00

    Great solution from this source

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

    This also works with spaces in the path!

    0 讨论(0)
  • 2020-12-12 23:08

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

    part1=`dirname "$p"`
    part2=`basename "$p"`
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题