Bash 重命名具有重复文件名的文件

Bash rename files with duplicated file names

我在移动我的一些文件时犯了一个错误,在我移动它们之后,它们以重复的文件名结束,中间有'-',例如:

Robot arm fails - Robot arm fails.mp4
this-is-another-file - this-is-another-file.txt
document - here - document - here.pdf

我想删除一半的名字: 例如:

Robot arm fails - Robot arm fails.mp4 -> Robot arm fails.mp4

this-is-another-file - this-is-another-file.txt -> this-is-another-file.txt

document - here - document - here.pdf -> document - here.pdf

我试过这段代码:

find . -type f -name "*-*" -exec bash -c 'f=""; g="${f/*-/}"; mv -- "$f" "$g"' - '{}' \;

但它不适用于名称中包含“-”的文件..

有什么想法吗?谢谢。

使用bash,很简单:

for fname in *; do
  # remove extension
  name="${fname%.*}"
  # extract the half and append extension
  echo mv -- "$fname" "${name::${#name}/2-1}.${fname##*.}"
done

如果输出看起来不错,请删除 echo

这是一个 awk 解决方案。类似于bash解决方案:

script.awk

{
    split([=10=],fileParts, "\.[^.]*$", ext); # split file to fileParts and extension
    newFileName = "'" substr(fileParts[1], 1, length(fileParts[1]) / 2 - 1) ext[1]"'"; # new fileName is: half fileParts and append extension
    cmd = "mv '" [=10=] "' " newFileName; # create a rename bash commmand from origin file name ([=10=]) and newFileName
    print cmd; # print bash command (for debug)
    #system(cmd); # execute bash command
}

这是一个调试版本,将打印重命名命令而不执行。

检查无误后执行。将 #system 替换为 system,然后再次替换 运行。

运行宁:

find . -type f -name "*-*" | awk -f script.awk