问题
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
...
回答1:
Try this in your mv
command:
mv "$f" "${f/.so/}"
First match of .so
is being replaced by empty string.
回答2:
a='opencv_calib3d.so2410.so'
echo "${a%%.so*}${a#*.so}"
opencv_calib3d2410.so
Where:
${a%%.so*}
- the part before the first.so
${a#*.so}
- the part after the first.so
来源:https://stackoverflow.com/questions/31252873/batch-remove-substring-from-filename-with-special-characters-in-bash