Package removes 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 are the result of a series of mistakes made with batch renames and now I cannot figure out how to remove the middle ".so" from each one. For example:

opencv_ocl.so2410.so

it should be opencv_ocl2410.so

Here's 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 they all fail, causing error messages:

mv: ‘opencv_calib3d.so2410.soandopencv_calib3d.so2410.soare the same file
mv: ‘opencv_contrib.so2410.soandopencv_contrib.so2410.soare the same file
mv: ‘opencv_core.so2410.soandopencv_core.so2410.soare the same file
...

      

+3


source to share


2 answers


Try the command mv

:

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

      



The first match .so

is replaced with an empty string.

+3


source


a='opencv_calib3d.so2410.so'
echo "${a%%.so*}${a#*.so}"
opencv_calib3d2410.so

      

Where:



  • ${a%%.so*}

    - part before the first .so

  • ${a#*.so}

    - part after the first .so

+3


source







All Articles