3

I just wrote a script that generated hundreds of files and stored them in a directory ~/foo. These files are ~/foo/X-file where X ranges from X=1 to X=900. My problem is that I would like to view these files in numerical order, but the files are not padded with zeros. Thus the directory contains 17-file and 544-file for example. Is there a way to pad these files with leading zeros?

3 Answers 3

5
cd ~/foo
for i in *-file; do
    num=${i%-file}
    padnum=$(printf '%03d' $num)
    mv -v "$i" "${padnum}-file"
done

Something along these lines should do it. Modify as necessary for precise patterns and directories.

4

If you have the Perl rename utility (often called prename, not the more primitive Linux one):

rename -v 's/^([0-9]-)/00$1/; s/^([0-9]{2}-)/0$1/' *-file
  • The first regular expression replaces single digits with two zeros (2->002)
  • The second one replaces two digits with with one zero (33->033)
-1

The following should work in bash if run in the directory you care about.

for x in [0-9]*-file ; do mv $x `printf %03d-%s ${x%-*} ${x##*-}` ; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .