Bash: rename 命令学习

有时候需要批量重命名一些文件
更新于: 2025-06-19 09:52:23

安装

# macos
brew install rename

# 确认安装完成
rename -h

常用命令

$ rename -h
Usage:
    rename [switches|transforms] [files]

    Switches:

    --man (read the full manual)
    -0/--null (when reading from STDIN)
    -f/--force or -i/--interactive (proceed or prompt when overwriting)
    -g/--glob (expand "*" etc. in filenames, useful in Windows™ CMD.EXE)
    -k/--backwards/--reverse-order
    -l/--symlink or -L/--hardlink
    -M/--use=Module
    -n/--just-print/--dry-run
    -N/--counter-format
    -p/--mkpath/--make-dirs
    --stdin/--no-stdin
    -t/--sort-time
    -T/--transcode=encoding
    -v/--verbose

    Transforms, applied sequentially:

    -a/--append=str
    -A/--prepend=str
    -c/--lower-case
    -C/--upper-case
    -d/--delete=str
    -D/--delete-all=str
    -e/--expr=code
    -P/--pipe=cmd
    -s/--subst from to
    -S/--subst-all from to
    -x/--remove-extension
    -X/--keep-extension
    -z/--sanitize
    --camelcase --urlesc --nows --rews --noctrl --nometa --trim (see manual)

日常用法

用法命令备注
添加前缀
# Dry run
$ rename -n 's/^/day250618_/' *
'001.pdf' would be renamed to 'day250618_001.pdf'
'002.pdf' would be renamed to 'day250618_002.pdf'

# 真实的执行
rename 's/^/day250618_/' *

# 添加带日期的前缀
rename -n "s/^/$(echo day$(date +%y%m%d)_)/" *
 
添加后缀
$ rename -n "s/$/$(echo __day$(date +%y%m%d))/" *
'001.pdf' would be renamed to '001.pdf__day250619'
'002.pdf' would be renamed to '002.pdf__day250619'

# 更合理的方式
$ rename -n "s/.pdf$/$(echo __day$(date +%y%m%d)).pdf/" *
'001.pdf' would be renamed to '001__day250619.pdf'
'002.pdf' would be renamed to '002__day250619.pdf'
 
批量修改文件后缀
# 将当前目录下的所有 .json 文件后缀修改为 .text
rename -S .json .text *.json
# 只一次替换(针对同一个文件名)
rename -s '#U00a9' 'safe' *
# 与上面等效
rename 's/\.json$/\.text/' *.json
# 带提示信息的
rename -v 's/\.json$/\.text/' *.json
# 正则
rename 's/([0-9][0-9])/$1-/' *
正则
去除文件后缀
# 将当前目录下的,所有 *.text 后缀都去掉
rename -x *.text
 
按索引方式指重命名
# 命令如下
rename -n -N ...001 -e '$_ = "$N-$_"' *.txt
# 输出信息
'example.txt' would be renamed to '1-example.txt'
'localized.txt' would be renamed to '2-localized.txt'

# 被全左侧信息
rename -n -N 001 -e '$_ = "$N-$_"' *.txt
# 输出信息
'example.txt' would be renamed to '001-example.txt'
'localized.txt' would be renamed to '002-localized.txt'

# 重命名,防止后缀名被影响
rename -n -N 001 -X -e '$_ = "$_-$N"' *.txt
# 输出信息
'example.txt' would be renamed to 'example-001.txt'
'localized.txt' would be renamed to 'localized-002.txt'
 
删除后缀名
# 清除后缀
rename -n -x *.txt

'example.txt' would be renamed to 'example'
'localized.txt' would be renamed to 'localized'
 
使用表达式
# -e 使用表达式,函数类似于c语言
rename -e 'printf("$_\n")' *.txt
 

小提示

  1. mac 下由于默认大小写不敏感,所以 --camelcase 会比较奇怪,所以,慎用这个选项(下面有举例)
  2. -v 可以用来显示修改的 infomation
  3. -n 可以用来 debug
$ rename --camelcase *.json
'package-lock.json' not renamed: 'Package-Lock.Json' already exists
'package.json' not renamed: 'Package.Json' already exists

参考