5

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
  • How do you want the numbers to be assigned? At random? Your example shows non-alphabetic, so I guess you don't care? – Wildcard May 8 '16 at 6:41
  • no ti should be sequential.. 01,02,03.. initial prefix is fixed (CO) – user3148655 May 8 '16 at 8:04
  • But you don't care if it's 01 - canada, 02 - france, 03 - england? So it's evidently random which sequence the files are handled in. – Wildcard May 8 '16 at 20:43
  • yes. you're correct – user3148655 May 9 '16 at 4:14
9

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.

  • Thank John! pretty much does what i want. but the second version does not increment the counter, and simply rename like CO_01_england.txt , CO_01_france.txt – user3148655 May 8 '16 at 6:58
  • @user3148655 The incrementation was inside a subshell, so it didn't stick. See the edited answer. – Gilles May 8 '16 at 20:06
1

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'

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.