Search code examples
bashshellrenamemv

Removing Middle Characters From File Name in Bash


I'm new to text handling in bash and have hundreds of files with varying names:

TS_01_001_21.0.tif
TS_10_005_-21.0.tif
TS_21_010_-45.0.tif

I want to remove the middle section and the extension so the files look like:

TS_01_21.0
TS_10_-21.0
TS_21_-45.0

So far I have:

for f in *.tif;do 
   mv "${f}" "${f%.tif}"
done

To remove the extension, but I can't figure out how to remove the middle three characters. Any help would be greatly appreciated, thank you!


Solution

  • Assumptions:

    • middle always means 3 digits plus an underscore (_)
    • there is only the one (aka middle) occurrence of 3 digits plus an underscore (_)
    • the extension is always .tif

    One idea using a pair of parameter substitutions to remove the unwanted characters:

    for f in TS_01_001_21.0.tif TS_10_005_-21.0.tif TS_21_010_-45.0.tif
    do
        newf="${f//[0-9][0-9][0-9]_/}"
        newf="${newf/.tif/}"
        if [[ -f "${newf}" ]] 
        then
            # addressing comment/question re: what happens if two source files are modified to generate the same new file name
            echo "WARNING: ${newf} already exists. [ source: ${f} ]"
        else
            echo mv "${f}" "${newf}"
        fi
    done
    

    This generates:

    mv TS_01_001_21.0.tif TS_01_21.0
    mv TS_10_005_-21.0.tif TS_10_-21.0
    mv TS_21_010_-45.0.tif TS_21_-45.0
    

    Once satisfied with the result OP can remove the echo in order to perform the actual file renames.