Search code examples
linuxbashfilenamesbatch-processingbatch-rename

Batch remove substring from filename with special characters in BASH


I have a list of files in my directory:

opencv_calib3d.so2410.so
opencv_contrib.so2410.so
opencv_core.so2410.so
opencv_features2d.so2410.so
opencv_flann.so2410.so
opencv_highgui.so2410.so
opencv_imgproc.so2410.so
opencv_legacy.so2410.so
opencv_ml.so2410.so
opencv_objdetect.so2410.so
opencv_ocl.so2410.so
opencv_photo.so2410.so

They're the product of a series of mistakes made with batch renames, and now I can't figure out how to remove the middle ".so" from each of them. For example:

opencv_ocl.so2410.so should be opencv_ocl2410.so

This is what I've tried:

# attempt 1, replace the (first) occurrence of `.so` from the filename
for f in opencv_*; do mv "$f" "${f#.so}"; done

# attempt 2, escape the dot
for f in opencv_*; do mv "$f" "${f#\.so}"; done

# attempt 3, try to make the substring a string
for f in opencv_*; do mv "$f" "${f#'.so'}"; done

# attempt 4, combine 2 and 3
for f in opencv_*; do mv "$f" "${f#'\.so'}"; done

But all of those have no effect, producing the error messages:

mv: ‘opencv_calib3d.so2410.so’ and ‘opencv_calib3d.so2410.so’ are the same file
mv: ‘opencv_contrib.so2410.so’ and ‘opencv_contrib.so2410.so’ are the same file
mv: ‘opencv_core.so2410.so’ and ‘opencv_core.so2410.so’ are the same file
...

Solution

  • Try this in your mv command:

    mv "$f" "${f/.so/}"
    

    First match of .so is being replaced by empty string.