Search code examples
bashvariablesawkzeropad

Add leading zeroes to awk variable


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.


Solution

  • Replace file on output with sprintf("%02d", file).

    Or even the whole assigment with filename = sprintf("%s_%02d.pdb", pdb, file);.