从 BASH 中的特殊字符批量删除文件名中的子字符串

Batch remove substring from filename with special characters in BASH

我的目录中有一个文件列表:

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

它们是批量重命名的一系列错误的产物,现在我不知道如何从它们中删除中间的“.so”。例如:

opencv_ocl.so2410.so 应该是 opencv_ocl2410.so

这是我试过的:

# 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

但是 所有 都没有效果,产生错误消息:

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
...
a='opencv_calib3d.so2410.so'
echo "${a%%.so*}${a#*.so}"
opencv_calib3d2410.so

其中:

  • ${a%%.so*} - 第一个 .so
  • 之前 的部分
  • ${a#*.so} - 第一个 .so
  • 之后 的部分

在您的 mv 命令中试试这个:

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

.so 的第一个匹配项正在替换为空字符串。