Linux shell script to add leading zeros to file names

后端 未结 10 1631
梦如初夏
梦如初夏 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:39

    To provide a solution that's cautiously written to be correct even in the presence of filenames with spaces:

    #!/usr/bin/env bash
    
    pattern='%04d'  # pad with four digits: change this to taste
    
    # enable extglob syntax: +([[:digit:]]) means "one or more digits"
    # enable the nullglob flag: If no matches exist, a glob returns nothing (not itself).
    shopt -s extglob nullglob
    
    for f in [[:digit:]]*; do               # iterate over filenames that start with digits
      suffix=${f##+([[:digit:]])}           # find the suffix (everything after the last digit)
      number=${f%"$suffix"}                 # find the number (everything before the suffix)
      printf -v new "$pattern" "$number" "$suffix"  # pad the number, then append the suffix
      if [[ $f != "$new" ]]; then                   # if the result differs from the old name
        mv -- "$f" "$new"                           # ...then rename the file.
      fi
    done
    

提交回复
热议问题