Delete everything before last / in bash

后端 未结 4 2095
无人共我
无人共我 2021-01-04 22:48

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 pri

4条回答
  •  春和景丽
    2021-01-04 23:45

    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.

提交回复
热议问题