Renaming a set of files to 001, 002, … on Linux

后端 未结 6 543
离开以前
离开以前 2020-12-05 07:51

I originally had a set of images of the form image_001.jpg, image_002.jpg, ...

I went through them and removed several. Now I\'d like to rename the leftover files ba

相关标签:
6条回答
  • 2020-12-05 08:07

    If I understand right, you have e.g. image_001.jpg, image_003.jpg, image_005.jpg, and you want to rename to image_001.jpg, image_002.jpg, image_003.jpg.

    EDIT: This is modified to put the temp file in the current directory. As Stephan202 noted, this can make a significant difference if temp is on a different filesystem. To avoid hitting the temp file in the loop, it now goes through image*

    i=1; temp=$(mktemp -p .); for file in image*
    do
    mv "$file" $temp;
    mv $temp $(printf "image_%0.3d.jpg" $i)
    i=$((i + 1))
    done                                      
    
    0 讨论(0)
  • 2020-12-05 08:13

    I was going to suggest something like the above using a for loop, an iterator, cut -f1 -d "_", then mv i i.iterator. It looks like it's already covered other ways, though.

    0 讨论(0)
  • 2020-12-05 08:16

    Some good answers here already; but some rely on hiding errors which is not a good idea (that assumes mv will only error because of a condition that is expected - what about all the other reaons mv might error?).

    Moreover, it can be done a little shorter and should be better quoted:

    for file in *; do
        printf -vsequenceImage 'image_%03d.jpg' "$((++i))"
        [[ -e $sequenceImage ]] || \
            mv "$file" "$sequenceImage"
    done
    

    Also note that you shouldn't capitalize your variables in bash scripts.

    0 讨论(0)
  • 2020-12-05 08:25

    A simple loop (test with echo, execute with mv):

    I=1
    for F in *; do
      echo "$F" `printf image_%03d.jpg $I`
      #mv "$F" `printf image_%03d.jpg $I` 2>/dev/null || true
      I=$((I + 1))
    done
    

    (I added 2>/dev/null || true to suppress warnings about identical source and target files. If this is not to your liking, go with Matthew Flaschen's answer.)

    0 讨论(0)
  • 2020-12-05 08:27

    This does the reverse of what you are asking (taking files of the form *.jpg.001 and converting them to *.001.jpg), but can easily be modified for your purpose:

    for file in * 
    
    do
    
    if [[ "$file" =~ "(.*)\.([[:alpha:]]+)\.([[:digit:]]{3,})$" ]]
    
    then
    
    mv "${BASH_REMATCH[0]}" "${BASH_REMATCH[1]}.${BASH_REMATCH[3]}.${BASH_REMATCH[2]}"
    
    fi
    
    done
    
    0 讨论(0)
  • 2020-12-05 08:29

    Try the following script:

    numerate.sh

    This code snipped should do the job:

    ./numerate.sh -d <your image folder> -b <start number> -L 3 -p image_ -s .jpg -o numerically -r
    
    0 讨论(0)
提交回复
热议问题