2

Linux 批量修改文件名

 1 year ago
source link: https://xujinzh.github.io/2023/05/07/linux-rename-filenames-in-batches/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Linux 批量修改文件名

发表于2023-05-07|更新于2023-05-07|technologylinux
字数总计:5.1k|阅读时长:NaN:aN分钟|阅读量:7

Linux 中有一些命令能够非常方便的修改文件名,如 rename 等。本篇注意介绍 Ubuntu 系统中该命令的一般使用方法。

# Debian/Ubuntu 安装方法
sudo apt update
sudo apt install -y rename

# Mac 安装方法
brew install rename

本篇介绍的 rename 版本是 Perl 版本,还有 C 版本,使用方法参见博文:Linux 批处理:修改文件名和文件内容

Linux 中修改单个文件名的方法是 mv 命令,我们可以借助管道符修改多个文件的文件名:

ls `pwd`
# 结果如下,包含两个以 .txt 结尾的文件
# hello.txt world.txt

# 修改文件扩展名为 .py
find `pwd` -name '*.txt' | awk -F '.' '{print $1}' | xargs -I {} mv {}.txt {}.py

rename 修改文件扩展名

使用 rename 修改扩展名更简洁

# 把以 txt 结尾($表示结尾)的文件改为 py 结尾
rename 's/txt$/py/' *.txt
# 递归修改子文件夹里扩展名 .sh 的文件为 .py
find . -name "*.sh" -type f | xargs -I {} rename 's/.sh/.py/' {}

# 删除文件扩展名
rename 's/.txt$//' *.txt

# 增加文件扩展名
rename 's/$/.txt/' *

文件名大小写

# 批量把文件名改为大写
rename 'y/a-z/A-Z/' *

# 批量把文件名改为小写
rename 'y/A-Z/a-z/' *

文件名前增加字段

# 在文件名前增加 new_ 字段
# ^ 匹配文件名开头
rename 's/^/new_/' *


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK