Walker News

Uses Awk To Add Leading Zero For A Number Value

Question: How to add leading zero to an integer value in Bash shell script?

Answer: It’s a piece of cake. Just use the awk command to do it.

When I develop a Bash script for pruning DB2 log files, I use the current log number minus 5 to derive the prior log file name for “db2 prune” command. Because the log file name is standardized as S<7-digit>.LOG, the script have to add zeros in front of the derived number, make sure the number is made up by 7 digits.

In brief:

If db2pd -d mydb -logs returns “current log number” as 7 to a variable called CurLogNo, then awk command should return prior log file name as S0000002.LOG for “db2 prune” command:
PriorLogFile=$((CurLogNo - 5))

echo $PriorLogFile | awk '{printf "S%07d.LOG",$1}'

Another simple example: get awk to print a given number in format that consists of at least 3 digits, i.e. if it’s less than 3 digits, add leading zeros to it:
[ root@local ] echo "7" | awk '{printf "%03d\n",$1}'
007
[ root@local ] echo "777" | awk '{printf "%03d\n",$1}'
777
[ root@local ] echo "7777" | awk '{printf "%03d\n",$1}'
7777

With reference to GNU Awk manual on modifiers for printf formats.

Custom Search

2014  •  Privacy Policy