通过在 bash 中重新排序模式来重命名文件

Rename files by reordering pattern in bash

我有一个 pdf 格式的文件:

Author-YYYY-rest_of_text_seperated_by_underscores.pdf
John-2010-some_file.pdf
Smith-2009-some_other_file.pdf

我需要重命名文件,以便年份在前,例如

YYYY-Author-rest_of_text_seperated_by_underscores.pdf
2010-John-some_file.pdf
2009-Smith-some_other_file.pdf

所以这意味着将 'YYYY-' 元素移动到开头。

我没有 unix 'Rename' 并且必须依赖 sed,awk etc.I 很高兴就地重命名。

我一直在尝试调整这个答案,但运气不佳。 Using sed to mass rename files

请参阅 BashFAQ #100 for general advice on string manipulation with bash. One of the techniques this goes into is parameter expansion,它在以下内容中被大量使用:

pat=-[0-9][0-9][0-9][0-9]-
for f in *$pat*; do  # expansion not quoted here to expand the glob
  prefix=${f%%$pat*} # strip first instance of the pattern and everything after -> prefix
  suffix=${f#*$pat}  # strip first instance and everything before -> suffix 
  year=${f#"$prefix"}; year=${year%"$suffix"} # find the matched year itself
  mv -- "$f" "${year}-${prefix}-${suffix}"    # ...and move.
done

顺便说一下,BashFAQ #30 讨论了很多重命名机制,其中一个使用 sed 到 运行 任意转换。

使用 BASH 正则表达式:

re='^([^-]+-)([0-9]{4}-)(.*)$'

for f in *.pdf; do
    [[ $f =~ $re ]] &&
    echo mv "$f" "${BASH_REMATCH[2]}${BASH_REMATCH[1]}${BASH_REMATCH[3]}"
done

如果您对 mv.

之前的输出删除 echo 命令感到满意