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

时间:2019-11-10 12:32:59

标签: bash sh

在移动某些文件时我犯了一个错误,当我移动它们后,它们最终得到了重复的文件名,中间带有'-',例如:

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="$1"; g="${f/*-/}"; mv -- "$f" "$g"' - '{}' \;

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

有什么想法吗?谢谢。

2 个答案:

答案 0 :(得分:1)

使用bash很容易:

saSample

如果输出看起来不错,请删除for fname in *; do # remove extension name="${fname%.*}" # extract the half and append extension echo mv -- "$fname" "${name::${#name}/2-1}.${fname##*.}" done

答案 1 :(得分:0)

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

script.awk

{
    split($0,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 '" $0 "' " newFileName; # create a rename bash commmand from origin file name ($0) and newFileName
    print cmd; # print bash command (for debug)
    #system(cmd); # execute bash command
}

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

在检查正确性后执行。将#system替换为system,然后再次运行。

正在运行:

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