Issue
I need 6th column of a csv file to be padded with zeroes but when I try with below command, it just replaces the actual value to 0000.
awk -F',' -v OFS=',' '{$6 = sprintf("%04d", $6); print}' $Input
Input:
"xx","x","xxxxxx","xxx","xx","123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","23","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","3","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
Output:
"xx","x","xxxxxx","xxx","xx","0123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0023","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0003","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
Solution
You may use this awk
with a custom field separator ","
:
awk 'BEGIN {FS=OFS="\",\""} {$6 = sprintf("%04d", $6)} 1' file
"xx","x","xxxxxx","xxx","xx","0123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0023","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0003","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
Answered By - anubhava