重命名文件的脚本

时间:2019-01-09 09:15:50

标签: shell file rename

我正试图编写一个脚本来批量重命名文件夹中的文件,就像这样:

文件名: LC PartA-PartB.pdf

将成为 LC PartB-PartA.pdf

因此,基本上,在“-”之后的所有内容都应在“-”之前,而在“-”之前的所有内容都应在“-”之后,除了前三个字符(“ LC” )。

有人吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

I went for find with while read. find finds files that match the regex LC <anything> - <anything>.pdf. For each matching file, I switch the parts using sed and then call mv:

find . -type f -regex '\./LC .* - .*\.pdf' |
while IFS= read -r file; do
    newfile=$(echo "$file" | sed 's/LC \(.*\) - \(.*\)\.pdf/LC \2 - \1 .pdf/')
    mv -v "$file" "$newfile"
done

For simplicity and when not handling some strange corcer-cases (like directories named the same way, ex.), you can go with a good old for:

for file in "LC "*" - "*".pdf"; do
    newfile=$(echo "$file" | sed 's/LC \(.*\) - \(.*\)\.pdf/LC \2 - \1 .pdf/')
    mv -v "$file" "$newfile"
done

I have tested using tutorialspoint