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

时间:2017-03-07 17:03:02

标签: bash rename

我有以下格式的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等。我很乐意在地方重命名。

我一直试图让这个答案适应没有多少运气。 Using sed to mass rename files

2 个答案:

答案 0 :(得分:4)

有关使用bash进行字符串操作的一般建议,请参阅BashFAQ #100。其中一种技术是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来运行任意转换。

答案 1 :(得分:3)

使用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

如果您对echo之前的输出删除mv命令感到满意。