Search code examples
regexbashrenamefilenamesbatch-processing

Delete sections from a list of filenames while maintaining a unique identifier coming after deleted section using Bash Command


Thanks in advance to this exceptional community. Please help with my first post ever! I have been trying to write a command to delete sections of filenames, but cannot figure out how to do so while maintaining the unique identifier that comes after the area I want to delete.

Here examples of the original filenames (I have o folder full of such):

101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=0.tif
101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=1.tif
101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=2.tif
101 OD_1_20x_L Rho GFP__02.vsi - C=0.tif
101 OD_1_20x_L Rho GFP__02.vsi - C=1.tif
101 OD_1_20x_L Rho GFP__02.vsi - C=2.tif

And the desired result:

101 OD_1_20x_L Rho GFP__01- C=0.tif
101 OD_1_20x_L Rho GFP__01- C=1.tif
101 OD_1_20x_L Rho GFP__01- C=2.tif
101 OD_1_20x_L Rho GFP__02- C=0.tif
101 OD_1_20x_L Rho GFP__02- C=1.tif
101 OD_1_20x_L Rho GFP__02- C=2.tif

I have been using variations on the following, but have not found a way to conserve the unique C=#.tif at the end of each file.

for f in ./*; do mv "$f" "$f%.vsi*C=*.tif}.tif" ; done 
for f in ./*; do mv "$f" "${f%.vsi*}C=*.tif" ; done

Solution

  • Do two splits by removing the last space separated string and then remove the .vsi part

    Something like this

    for f in *.tif; do
        echo mv -v -- "$f" "${f%.vsi*} - ${f##* }"
    done
    

    Remove the echo if you think the output is correct.

    This is the output without the echo

    renamed '101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=0.tif' -> '101 OD_1_20x_L Rho GFP__01 - C=0.tif'
    renamed '101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=1.tif' -> '101 OD_1_20x_L Rho GFP__01 - C=1.tif'
    renamed '101 OD_1_20x_L Rho GFP__01.vsi - macro image - C=2.tif' -> '101 OD_1_20x_L Rho GFP__01 - C=2.tif'
    renamed '101 OD_1_20x_L Rho GFP__02.vsi - C=0.tif' -> '101 OD_1_20x_L Rho GFP__02 - C=0.tif'
    renamed '101 OD_1_20x_L Rho GFP__02.vsi - C=1.tif' -> '101 OD_1_20x_L Rho GFP__02 - C=1.tif'
    renamed '101 OD_1_20x_L Rho GFP__02.vsi - C=2.tif' -> '101 OD_1_20x_L Rho GFP__02 - C=2.tif'