Search code examples
bashshellsh

Remove all letters between two underscores with shell script


My directory has a list of filenames similar to _3vaca3424434_1-lecture-introduction.pdf and I want to rename it as 1-lecture-introduction.pdf. How can I do that?


Solution

  • for f in *; do
        new_f=${f##_*_}
        echo mv -- "$f" "$new_f"
    done
    

    Review the output of the above, and if the commands look right, remove the echo and run again.

    ${f##_*_} removes the longest prefix matching the pattern _*_ from the value of $f.