Reputation: 18670
I have a folder containing the following files:
trackingData-00-1.data, trackingData-00-2.data, ..., trackingData-00-2345.data
And I would like to rename them by formatting numbers with 4 digits
trackingData-00-0001.data, trackingData-00-0002.data, ..., trackingData-00-2345.data
How can I achieve that with a bash shell command?
Upvotes: 3
Views: 4708
Reputation: 289565
You can use printf
's options in awk to print four digits:
echo 3 | awk '{printf ("%04i", $1)}'
0003
echo 33 | awk '{printf ("%04i", $1)}'
0033
So it could be:
for file in trackingData*
do
num=$(awk -F[.-] '{printf ("%04i", $3)}' <<< "$file")
mv $file trackingData-00-$num.data
done
This uses awk
with both field separators: either .
or -
. Then, it takes the 3rd block based on them and formats its value with the %04i
flag (almost equivalent to %d
as seen in The GNU Awk User’s Guide #5.5.2 Format-Control Letters).
Upvotes: 2
Reputation: 531055
A pure bash
solution:
for f in trackingData-00-*.data; do
[[ $f =~ trackingData-00-([0-9]+).data ]]
mv "$f" $(printf "trackingData-00-%04d.data" ${BASH_REMATCH[1]})
done
A regular expression extracts the number to pad and stores it in the BASH_REMATCH
array. Then printf
is used to create the new file name, with the number reinserted and padded with zeros.
Upvotes: 7
Reputation: 876
dirty but working hack:
for i in $(seq 2345); do
mv trackingData-00-$i.data trackingData-00-`printf %04d $i`.data;
done
Upvotes: 2
Reputation: 195039
first of all, I assume that there is no spaces in your file name. then
ls/find...| awk -F'-|\\.' '{o=$0;$3=sprintf("%04d",$3);$4=".data";gsub(/-\./,".");print "mv "o" "$0}' OFS='-'
will print the mv ...
command. to execute them, just pipe the output to sh
like
ls...|awk ..|sh
the core is the awk part, test it a bit:
kent$ echo "trackingData-00-1.data
trackingData-00-2.data"|awk -F'-|\\.' '{o=$0;$3=sprintf("%04d",$3);$4=".data";gsub(/-\./,".");print "mv "o" "$0}' OFS='-'
mv trackingData-00-1.data trackingData-00-0001.data
mv trackingData-00-2.data trackingData-00-0002.data
Upvotes: 1