namu
namu

Reputation: 146

rename directories padded with zeros using bash

I am trying to rename a large number of directories so that they are padded with zeros. I am trying to run the bash script in the directory workingDir containing the viz directory. In the viz directory, I have directories

visit_dump.0001
visit_dump.0005 visit_dump.11000 visit_dump.12000 visit_dump.504000

How can I rename them to the following?

visit_dump.000001
visit_dump.000005 visit_dump.011000 visit_dump.012000 visit_dump.504000

Also, I do not know if the directory with the largest extension, here being 504000 will have 6 digits or more or less.

Below is an attempt with very strange results ( I get the message printf: 04800: invalid octal number and it assigns completely the wrong extension to the directory. Any help will be appreciated. Thank you.

eulerDir=visit_dump

dataDir=viz

cd ./$dataDir

for eulerDirIter in $(ls -d $eulerDir.*); do
    number=$(echo $eulerDirIter |awk -F . '{print $NF}')
    $(mv $eulerDirIter $(printf $eulerDir.%06d $number));
done

Upvotes: 1

Views: 141

Answers (2)

glenn jackman
glenn jackman

Reputation: 246799

Finds the largest numeric extension in the first line, and handles each number as decimal not octal:

max=$(for f in *; do echo "${f##*.}"; done | sort -n | tail -1)
for f in *; do
    base=${f%.*}
    ext=${f##*.}
    newext=$(printf "%0*d" ${#max} "$((10#$ext))")
    echo mv "$f" "$base.$newext"
done

Upvotes: 3

Faiz
Faiz

Reputation: 16245

Try this hack:

awk -F . '{print $NF+0}'

The issue was that any number that starts with a 0 is treated as octal. So while 0005 in octal is the same as 5 decimal, a string like 04800 is treated as octal but unfortunately contains an 8 which makes it an illegal octal number.

You use awk -F . '{print $NF}' to get at the numerical suffix of the directories, but you want to treat them as numbers, so a simple way to convert the string 04800 to a number is to simple add 0 to it. (awk does not treat 04800 as octal).

Upvotes: 1

Related Questions