0

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!

2
  • 1
    what should happen if you have filenames like TS_01_001_21.0.tif and TS_01_002_21.0.tif ? Commented Oct 24, 2022 at 21:05
  • For such complex name transformations, you are perhaps fastest, if you use the bash regex operator, which can not only match a tring for having a certain structure, but also extract parts of the string. It is described in the bash man-page in the section Compound Commands, under the command [[ expression ]]. In addition, I would consider using the option -i for mv. Commented Oct 25, 2022 at 9:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.