使用BASH中的特殊字符从文件名中删除子字符串

时间:2015-07-06 18:17:18

标签: linux bash filenames batch-processing batch-rename

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

public static void deleteFilesForPathByPrefix(final Path path, final String prefix) {
    try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path, prefix + "*")) {
        for (final Path newDirectoryStreamItem : newDirectoryStream) {
            Files.delete(newDirectoryStreamItem);
        }
    } catch (final Exception e) { // empty
    }
}

它们是批量重命名产生的一系列错误的产物,现在我无法弄清楚如何从每个错误中删除中间的“.so”。例如:

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 应为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

2 个答案:

答案 0 :(得分:3)

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

其中:

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

答案 1 :(得分:3)

mv命令中尝试此操作:

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

.so的第一场比赛正在被空字符串取代。