Linux shell script to add leading zeros to file names

后端 未结 10 1606
梦如初夏
梦如初夏 2020-12-04 06:43

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 filena

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 07:29

    Using the rename (prename in some cases) script that is sometimes installed with Perl, you can use Perl expressions to do the renaming. The script skips renaming if there's a name collision.

    The command below renames only files that have four or fewer digits followed by a ".txt" extension. It does not rename files that do not strictly conform to that pattern. It does not truncate names that consist of more than four digits.

    rename 'unless (/0+[0-9]{4}.txt/) {s/^([0-9]{1,3}\.txt)$/000$1/g;s/0*([0-9]{4}\..*)/$1/}' *
    

    A few examples:

    Original    Becomes
    1.txt       0001.txt
    02.txt      0002.txt
    123.txt     0123.txt
    00000.txt   00000.txt
    1.23.txt    1.23.txt
    

    Other answers given so far will attempt to rename files that don't conform to the pattern, produce errors for filenames that contain non-digit characters, perform renames that produce name collisions, try and fail to rename files that have spaces in their names and possibly other problems.

提交回复
热议问题