-2

I have file names (from image tiles) consisting of two numbers separated by an underscore, e.g.

142_27.jpg
7_39.jpg
1_120.jpg

How can I (in linux) add leading zeros to both of these numbers? What I want is the file names as

142_027.jpg
007_039.jpg
001_120.jpg
Sundeep
  • 23,246
  • 2
  • 28
  • 103
user1583209
  • 1,637
  • 3
  • 24
  • 42
  • you are looking to rename files or change text in a file? – Sundeep Nov 23 '16 at 15:14
  • Rename files. I found many examples for adding zeros to the start of a file name, but here I want zeros in two places (at the beginning and after the underscore.) – user1583209 Nov 23 '16 at 15:15

4 Answers4

2

You can use a single awk command to format filenames with leading zeroes using a printf:

for f in *.jpg; do
   echo mv "$f" $(awk -F '[_.]' '{printf "%03d_%03d.%s", $1, $2, $3}' <<< "$f")
done

This will output:

mv 142_27.jpg 142_027.jpg
mv 1_120.jpg 001_120.jpg
mv 7_39.jpg 007_039.jpg

Once you're satisfied with the output, remove echo before mv command.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

With perl based rename command

$ touch 142_27.jpg 7_39.jpg 1_120.jpg
$ rename -n 's/\d+/sprintf "%03d", $&/ge' *.jpg
rename(1_120.jpg, 001_120.jpg)
rename(142_27.jpg, 142_027.jpg)
rename(7_39.jpg, 007_039.jpg)

The -n option is for dry run, remove it for actual renaming


If perl based rename command is not available:

$ for f in *.jpg; do echo mv "$f" "$(echo "$f" | perl -pe 's/\d+/sprintf "%03d", $&/ge')"; done
mv 1_120.jpg 001_120.jpg
mv 142_27.jpg 142_027.jpg
mv 7_39.jpg 007_039.jpg

Change echo mv to just mv once dry run seems okay

Sundeep
  • 23,246
  • 2
  • 28
  • 103
0

You can do it with a little shell-script using sed:

for i in *.jpg;
do
    new=`echo "$i" | sed -n -e '{ s/^\([0-9]\{0,3\}\)_\([0-9]\{0,3\}\).jpg/000\1_000\2.jpg/ };
    {s/\([0-9]*\)\([0-9]\{3\}\)_\([0-9]*\)\([0-9]\{3\}\).jpg/\2_\4.jpg/p };'`;
    mv "$i" "$new";
done;

I first append three leading zeros at the said places by default and afterwards cut off as many digits as necessary brginning at the start at said places so that only 3 digits are left

FloHe
  • 313
  • 1
  • 3
  • 10
0

with bash substitution(a,b)

windows(bash)

for f in *.jpg;do a=${f%_*};b=${f#*_};mv $f $(printf "%03d_%07s" $a $b);done

linux

for f in *.jpg;do a=${f%_*};b=${f#*_};b=${b%.*};mv $f $(printf "%03d_%03d".jpg $a $b);done
jns
  • 251
  • 2
  • 4