Search code examples
fileawksedrenamemv

How to decrease number in filename list by sed or similar tool


I have a list of files numbered in the filename, starting eg. at 013 (or another count) but want them renamed to start by 001. I don't mind the tool used (awk, sed, mv, tr, what-ever...)

Example (before -> after):

img013.tif -> img001.tif
img014.tif -> img002.tif
...

etc.

Appreciate any help. 1000 x thanks, Roland


Solution

  • Since a glob expression will retrieve the file list in alphabetical (alphanumerical) order you can simply use this:

    #!/bin/bash
    
    i=0
    # The loop iterates over tif files in alphanumerical order
    for file in *.tif ; do
        mv -v "$file" "img$(printf "%03d" "$i").tif"
        i=$((i+1))
    done