BASH file mass rename with counter

I want to rename all the files in a folder with PREFIX+COUNTER+FILENAME

for ex.
input:

england.txt  
canada.txt  
france.txt

output:

CO_01_england.txt  
CO_02_canada.txt  
CO_03_france.txt

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This does what you ask:

n=1; for f in *.txt; do mv "$f" "CO_$((n++))_$f"; done

How it works

  • n=1

    This initializes the variable n to 1.

  • for f in *.txt; do

    This starts a loop over all files in the current directory whose names end with .txt.

  • mv "$f" "CO_$((n++))_$f"

    This renames the files to have the CO_ prefix with n as the counter. The ++ symbol tells bash to increment the variable n.

  • done

    This signals the end of the loop.

Improvement

This version uses printf which allows greater control over how the number will be formatted:

n=1; for f in *.txt; do mv "$f" "$(printf "CO_%02i_%s" "$n" "$f")"; ((n++)); done

In particular, the %02i format will put a leading zero before the number when n is still in single digits.

Method 2

With the prename utility found on Debian and derivatives or available on other systems by installing the Perl package Unicode::Tussle:

prename 's ([^/]*z) (sprintf("C0_%02d_%s", ++$n, $&))e' england.txt canada.txt france.txt

Explanation: for each argument, rename the base name (the longest suffix not containing a slash) to C0_ followed by the counter value $n (incremented before use, starting at 0 before the first incrementation and use) formatted to two decimal digits, followed by _, followed by the original name. To rename all files with the .txt extension, with the numbering in lexicographic order:

prename 's ([^/]*z) (sprintf("C0_%02d_%s", ++$n, $&))e' *.txt

With zsh, use the zmv function, and the parameter expansion flag l to pad the number:

autoload -U zmv
zmv '*.txt' '$f:h/C0_${(l:2::0:)$((++x))}_$f:t'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x