Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Appending a counting suffix to input files with increment of 1 1

Status
Not open for further replies.

bazil2

Technical User
Feb 15, 2010
148
DE
(Elementary user)

I would like to make a script that when executed renames the files in a directory by adding a number that increments by the value of '1' with each file it processes.

For example:

My_first_file.jpg
Another_file.jpg
ABC_file.jpg

Will be renamed to:

My_first_file_001.jpg
Another_file_002.jpg
ABC_file_003.jpg

Can anyone give me any pointers, I would like to use a shell script if possible?

Best regards
 
Code:
$ j=1
$ for i in *.jpg ; do 
  f1=`basename $i .jpg`
  f2=`printf "%s_%03d.jpg" $f1 $j`
  echo mv $i $f2
  ((j++))
done
mv ABC_file.jpg ABC_file_001.jpg
mv Another_file.jpg Another_file_002.jpg
mv My_first_file.jpg My_first_file_003.jpg
This works if you have a bash shell. The printf command is GNU specific, so you might need some other approach.



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Actually, printf is fairly ubiquitous, so it should work on most flavour of Unix. In bash it's a shell builtin, but in other cases (HP-UX, ...?) there is a /usr/bin/printf binary to save the day.

Annihilannic.
 
You have to mask $i, $f1, $f2 because they may contain whitespace:
Code:
for i in *.jpg 
do
    f1=$(basename "$i" .jpg)
    f2=$(printf "%s_%03d.jpg" "$f1" $j)
    mv "$i" "$f2" 
    ((j++))
done
Backticks are deprecated, so use $(...) instead. It's better readable, writeable and nestable.

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top