Linux shell 脚本为文件名添加前导零 [英] Linux shell script to add leading zeros to file names
问题描述
我有一个包含大约 1,700 个文件的文件夹.它们都被命名为 1.txt
或 1497.txt
等.我想重命名所有文件,以便所有文件名都是四位数.
I have a folder with about 1,700 files. They are all named like 1.txt
or 1497.txt
, etc. I would like to rename all the files so that all the filenames are four digits long.
即,23.txt
变成 0023.txt
.
可以执行此操作的 shell 脚本是什么?或者一个相关的问题:如何使用 grep 只匹配包含 d.txt
的行(即,一个数字,然后是一个句点,然后是字母 txt
)?
What is a shell script that will do this? Or a related question: How do I use grep to only match lines that contain d.txt
(i.e., one digit, then a period, then the letters txt
)?
这是我目前所拥有的:
for a in [command i need help with]
do
mv $a 000$a
done
基本上,运行 3 次,并在那里使用命令来查找一位、两位和三位文件名(更改了初始零的数量).
Basically, run that three times, with commands there to find one digit, two digits, and three digit filenames (with the number of initial zeros changed).
推荐答案
尝试:
for a in [0-9]*.txt; do
mv $a `printf %04d.%s ${a%.*} ${a##*.}`
done
根据需要更改文件名模式 ([0-9]*.txt
).
Change the filename pattern ([0-9]*.txt
) as necessary.
通用枚举重命名,不对初始文件名集做任何假设:
A general-purpose enumerated rename that makes no assumptions about the initial set of filenames:
X=1;
for i in *.txt; do
mv $i $(printf %04d.%s ${X%.*} ${i##*.})
let X="$X+1"
done
<小时>
关于同一主题:
这篇关于Linux shell 脚本为文件名添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!