Bash – Shorten Linux Filename (truncate on a symbol)

bashlinuxrename

I have a list of files in Linux that I want to shorten. They are in the following format: WhatIWant_WhatIDoNotWant.txt.

Is there an easy way to make them: WhatIWant.txt? I saw the following question (link below) and I really like the for do loop (just in case the result has a duplicate), but I don't know how to get the place value of the underscore (_) to feed that in instead of using the 16th character as the ending point…

Linux script or program to shorten filenames

Best Answer

# We loop over the files with filename suffix .txt

for f in *.txt; do
    # We rename the file removing _ and the remaining part including the extension
    mv -- "$f" "${f/_*}.txt"
done
Related Question