Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 884
mirix Avatar asked Sep 05 '25 16:09

mirix


2 Answers

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).

like image 81
JJ. Avatar answered Sep 07 '25 18:09

JJ.


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

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

like image 30
glglgl Avatar answered Sep 07 '25 17:09

glglgl