Programming and Scripting :: Need help with bash



Hello,

I need help writing a piece of bash.

What I am trying to do is get a bash script to target single digit file names and convert them to double digits. Lets say this is what I have in my folder:

1.jpg
10.jpg
11.jpg
12.jpg
2.jpg
20.jpg
3.jpg
4.jpg
5.jpg
1.txt
2.txt

I would like the bash script to rename 1.jpg, 2.jpg, 3.jpg, 4.jpg, and 5.jpg into 01.jpg, 02.jpg, 03.jpg, 04.jpg and 05.jpg. At the same time not mistakening the 11.jpg and 12.jpg as as 1.jpg and 2.jpg

The bash script will only target *.jpg formats so conflicts with 1.txt and 2.txt does not occour.

Okay, this is my newbism:

Code Sample

seq=(`seq 1 9`)
file=(ls $seq.jpg)
if $file
then
for loop in $file
do
mv $loop 0$loop
done


Like I said, my newbism.

How do I make this script functional? Please help.

Thanks in advance.

moved the the appropriate area.

~J.P.
Try using the "awk" or "gawk" programs to parse the filename straing and report back the size of the filename in characters.

Search google for

man awk

or maybe

awk guide

awk help

to learn more about how to use the awk command.

ramdisc, I was able to do it in bash as follows (the whole thing is on a single line):

ls [0-9].jpg | cut -d "." -f1 | while read i ; do mv "$i.jpg"  "0$i.jpg" ; done

ls [0-9].jpg returns only files that start with a single digit and end in .jpg.  This gets piped into cut, which breaks the input lines on the periods and returns field one (the part before the period).  While read i sets up a loop that sets the variable $i to each file's prefix and processes them individually.  Then mv moves the old name to the new name.

You could also then write a similar command line to change 2 number names in to three number names.

clacker,

You da man!  (or da woman, if appropriate)

No sissy awk scripts need apply.

Next Page...
original here.