Linux shell script to add leading zeros to file names

后端 未结 10 1530
梦如初夏
梦如初夏 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
    
    0 讨论(0)
  • 2020-12-04 07:40

    To only match single digit text files, you can do...

    $ ls | grep '[0-9]\.txt'
    
    0 讨论(0)
  • 2020-12-04 07:40

    One-liner hint:

    while [ -f ./result/result`printf "%03d" $a`.txt ]; do a=$((a+1));done
    RESULT=result/result`printf "%03d" $a`.txt
    
    0 讨论(0)
  • 2020-12-04 07:45

    Try:

    for a in [0-9]*.txt; do
        mv $a `printf %04d.%s ${a%.*} ${a##*.}`
    done
    

    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
    

    On the same topic:

    • Bash script to pad file names
    • Extract filename and extension in bash
    0 讨论(0)
提交回复
热议问题