Add leading zeroes to awk variable

mirix picture mirix · Aug 24, 2011 · Viewed 47.2k times · Source

I have the following awk command within a "for" loop in bash:

awk -v pdb="$pdb" 'BEGIN {file = 1; filename = pdb"_" file ".pdb"}
 /ENDMDL/ {getline; file ++; filename = pdb"_" file ".pdb"}
 {print $0 > filename}' < ${pdb}.pdb 

This reads a series of files with the name $pdb.pdb and splits them in files called $pdb_1.pdb, $pdb_2.pdb, ..., $pdb_21.pdb, etc. However, I would like to produce files with names like $pdb_01.pdb, $pdb_02.pdb, ..., $pdb_21.pdb, i.e., to add padding zeros to the "file" variable.

I have tried without success using printf in different ways. Help would be much appreciated.

Answer

JJ. picture JJ. · Aug 24, 2011

Here's how to create leading zeros with awk:

# echo 1 | awk '{ printf("%02d\n", $1) }'
01
# echo 21 | awk '{ printf("%02d\n", $1) }'
21

Replace %02 with the total number of digits you need (including zeros).