Sorting Numbers for linux scripting

Solaris Unix essentials featuring the so...
January 10, 2011 at 00:52:33
Specs: Macintosh
Hi guys, I'm trying to sort through files that are listed 1-20, like File1, File10, File20, and then I want to do rename them so that they are padded to 4 digits. How would I do that, considering normally files would go File1, then File10? Thanks in Advance for any help!

See More: Sorting Numbers for linux scripting

Report •

#1
January 10, 2011 at 02:21:21
I think this should get the whole thing done...well, at least, on bash it works!


basical logic is:
get filenames;
strip string from filename;
strip number from filename;
check lengt of number part of filename;
add as much 0es as needed to number part;
rename file;

#!/bin/bash

path="/file/path/";
files="/file/path/*";

for file in $files; do {
name=$(basename $file);
echo $name;
newname=$(echo "$name" | sed "s/[0-9]//g")
oldnum=$(echo "$name" | sed "s/[^0-9]//g")

if [ ${#oldnum} -lt 2 ]; then
{
newnum=000$oldnum;
}
elif [ ${#oldnum} -lt 3 ]; then
{
newnum=00$oldnum;
}
elif [ ${#oldnum} -lt 4 ]; then
{
newnum=0$oldnum;
}
fi
newfile=$newname$newnum;
mv $file $path/$newfile;
}
done;


Report •
Related Solutions


Ask Question