如何重命名bash中目录中的文件组? 例如: 我有文件组:如何用增量重命名文件组
> 0001.txt
> 0002.txt
> 0003.txt
> 0004.txt
...
我需要0001.txt成为0002.txt; 0002.txt成为0003.txt等 而且结果应该是这样:
0002.txt
0003.txt
0004.txt
0005.txt
...
如何重命名bash中目录中的文件组? 例如: 我有文件组:如何用增量重命名文件组
> 0001.txt
> 0002.txt
> 0003.txt
> 0004.txt
...
我需要0001.txt成为0002.txt; 0002.txt成为0003.txt等 而且结果应该是这样:
0002.txt
0003.txt
0004.txt
0005.txt
...
如果你的文件名遵循给定的模式,你可以这样做:
for file in `ls | egrep '^[[:digit:]]+.txt$' | sort -r`
do
mv $file `printf %04d $(expr ${file%.*} + 1)`.txt
done
编辑
对于有前缀的文件名tet
可以修改上面这样的脚本:
for file in `ls | egrep '^tet[[:digit:]]+.txt$' | sort -r`
do
filename=${file%.*}
mv $file tet`printf %04d $(expr ${filename:3} + 1)`.txt
done
只是出于好奇,我想如果一些bash的专家知道的方式,以避免临时欣赏变量filename
但我应该写什么,如果文件不会“0001.txt”,但“tet0001.txt”? –
他们都有相同的前缀? –
是的,所有文件都有这个前缀 –
您可以使用下面简单的脚本: -
#!/bin/bash
while IFS= read -r -d '' file; do
filename=$(basename "$file") # Get the absolute path of the file
filename=${filename%.*} # Getting file-name without the extension part 'tet0002', 'tet0001'
filename=${filename:3} # Getting the numerical part '002', '001'
# To preserve the leading pad '0's, retaining the decimal representation
# using printf and appending '10#' notation. '-v' for verbose only (can
# be removed)
mv -v "$file" tet"$(printf %04d "$((10#$filename + 1))")".txt
done < <(find . -maxdepth 1 -mindepth 1 -name "tet*.txt" -type f -print0)
在操作中查看
$ ls tet*
tet0003.txt tet0005.txt tet0008.txt
$ ./script.sh
`./tet0005.txt' -> `tet0006.txt'
`./tet0008.txt' -> `tet0009.txt'
`./tet0003.txt' -> `tet0004.txt'
请注意这一点。如果你有文件'tet0005.txt'和'tet0006.txt',它看起来像'tet0006.txt'将在被重命名之前被最初的'tet0005.txt'的内容覆盖。请参阅ewcz对最初文章的评论。 –
@ThomasWilmotte:好的!感谢您的评论,我演示了一个使用这些数字的例子,作者在运行脚本时必须注意同样的事情。 – Inian
我不是bash的专家,但是你不能仅仅在你的循环结尾用'sort -r'来获取文件名按照反向字母顺序排序吗?这样,你可以避免这个问题。也许'find'有一些选项(需要检查的人) –
在这种情况下,从最后一个开始,以便您不会覆盖进程中的某些文件... :) – ewcz