linuxrenamesequential-number

renaming multiple sequential files extension


I have multiple sequential files naming in one directory with multiple incremental files extension. My objective is using rename command to rename just the file extension.

IBM0020.DAT_001
IBM0020.DAT_002
IBM0020.DAT_003
IBM0021.DAT_001
IBM0021.DAT_002
IBM0022.DAT_001
IBM0022.DAT_002
IBM0022.DAT_003
IBM0022.DAT_004
...

to

IBM0020.DAT_001
IBM0020.DAT_002
IBM0020.DAT_003    
IBM0021.DAT_004
IBM0021.DAT_005
IBM0022.DAT_006
IBM0022.DAT_007
IBM0022.DAT_008
IBM0022.DAT_009
...

I have dry run the command below, but not the expected result. I want to retain the filename and only rename/change the extension with running number sequence.

rename -n 's/.+/our $i;sprintf(".DAT_%03d",1+$i++)/e' *
IBM0020.DAT_001 renamed as .DAT_001
IBM0020.DAT_002 renamed as .DAT_002
IBM0020.DAT_003 renamed as .DAT_003
IBM0021.DAT_001 renamed as .DAT_004
IBM0021.DAT_002 renamed as .DAT_005
IBM0022.DAT_001 renamed as .DAT_006
IBM0022.DAT_002 renamed as .DAT_007
IBM0022.DAT_003 renamed as .DAT_008
IBM0022.DAT_004 renamed as .DAT_009

Thanks for any help.


Solution

  • Continuing from the comment, if all of your files have .DAT_XXX as the extension you wish to rename sequentially, then there is no need to include ".DAT_" as part of the pattern you are matching. Simply match the 3-digits at the end of the filename and change those, e.g.

    rename 's/\d{3}$/our $i; sprintf("%03d", 1+$i++)/e' *
    

    If ".DAT_" isn't unique, and you have other extensions ending in 3-digits you want to avoid renaming, then you can include "DAT_" as part of the pattern matched and replaced, e.g.

    rename -n 's/DAT_\d{3}/our $i; sprintf("DAT_%03d", 1+$i++)/e' *
    

    (note: there are two different "rename" utilities in common use on Linux, the first provided as part of the util-linux package does not support regex renaming, and then perl-rename, which you have, that does support perl-regex renaming.)