Chinaunix首页 | 论坛 | 博客
  • 博客访问: 948655
  • 博文数量: 481
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5078
  • 用 户 组: 普通用户
  • 注册时间: 2018-03-07 14:48
个人简介

分享工作和学习中的点点滴滴,包括前端、后端、运维、产品等各个方面,欢迎您来关注订阅!

文章分类

全部博文(481)

文章存档

2023年(26)

2022年(97)

2021年(119)

2020年(153)

2019年(70)

2018年(16)

我的朋友

分类: LINUX

2022-01-20 14:52:44

本教程将讨论将文件从特定扩展名更改为另一个扩展名的快速方法。我们将为此使用 循环、rename。
方法一:使用循环

在目录中递归更改文件扩展名的最常见方法是使用 shell 的 for 循环。我们可以使用 shell 提示用户输入目标目录、旧的扩展名和新的扩展名以进行重命名。以下是内容:

[root@localhost ~]# vim rename_file.sh
#!/bin/bash
echo "Enter the target directory "
read target_dir
cd $target_dir
 
echo "Enter the file extension to search without a dot"
read old_ext
 
echo "Enter the new file extension to rename to without a dot"
read new_ext
 
echo "$target_dir, $old_ext, $new_ext"
 
for file in *.$old_ext
do
    mv -v "$file" "${file%.$old_ext}.$new_ext"
done;

Centos8中如何更改文件夹中多个文件的扩展名Centos8中如何更改文件夹中多个文件的扩展名
上面的脚本将询问用户要处理的目录,然后 cd 进入设置目录。接下来,我们得到没有点.的旧扩展名。最后,我们获得了新的扩展名来重命名文件。然后使用循环将旧的扩展名更改为新的扩展名。

其中${file%.$old_ext}.$new_ext意思为去掉变量$file最后一个.及其右面的$old_ext扩展名,并添加$new_ext新扩展名。

使用mv -v,让输出信息更详细。

下面运行脚本,将/root/test下面的以.txt结尾的替换成.log:

[root@localhost ~]# chmod +x rename_file.sh 
[root@localhost ~]# ./rename_file.sh 
Enter the target directory 
/root/test
Enter the file extension to search without a dot
txt
Enter the new file extension to rename to without a dot
log
/root/test, txt, log
renamed 'file10.txt' -> 'file10.log'
renamed 'file1.txt' -> 'file1.log'
renamed 'file2.txt' -> 'file2.log'
renamed 'file3.txt' -> 'file3.log'
renamed 'file4.txt' -> 'file4.log'
renamed 'file5.txt' -> 'file5.log'
renamed 'file6.txt' -> 'file6.log'
renamed 'file7.txt' -> 'file7.log'
renamed 'file8.txt' -> 'file8.log'
renamed 'file9.txt' -> 'file9.log'

Centos8中如何更改文件夹中多个文件的扩展名Centos8中如何更改文件夹中多个文件的扩展名
如果想将.log结尾的更改回.txt,如下操作:


server.51cto.com/ManageDC-519389.htmCentos8中如何更改文件夹中多个文件的扩展名Centos8中如何更改文件夹中多个文件的扩展名

方法二:使用rename

如果不想使用脚本,可以使用rename工具递归更改文件扩展名。如下是使用方法:

[root@localhost ~]# cd /root/test/
[root@localhost test]# rename .txt .log *.txt

Centos8中如何更改文件夹中多个文件的扩展名Centos8中如何更改文件夹中多个文件的扩展名
更改回.txt扩展名也同样的操作:

[root@localhost test]# rename .log .txt *.log

Centos8中如何更改文件夹中多个文件的扩展名Centos8中如何更改文件夹中多个文件的扩展名

总结

本教程讨论了如何将文件从特定扩展名更改为另一个扩展名的快速方法。我们将为此使用 shell循环、rename命令。

阅读(362) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~