Left pad spaces using awk or sed

Hi,I've a unix pipe delimited file as below

f1|f2|f3|f4|f5|f6

My requirement is to pad spaces on the left to fields f2, f3 and f5. Field Lengths according to file layout f2 - 4 char f3 - 5 char f5 - 3 char If my record is as below

1|43|bc|h0|34|a

Output record should be as below

1|  43|   bc|h0| 34|a

Kindly provide a solution using awk or sed. Appreciate help! Regards,Soujanya

awk -F"|" '{printf "%d|%4d|%5d|%d|%3d|%d", $1,$2,$3,$4,$5,$6}' file

Hi,Thanks for the above solution. Since the file has string type data used %s instead of %d.

awk -F"|" '{printf "%s|%4s|%5s|%s|%3s|%s", $1,$2,$3,$4,$5,$6}' input_file
   But this awk statement becomes too lengthy if my source file has around 25 fields or more.    So let me know if any simple awk or sed can be used to achieve the same.  Regards,Soujanya

try:

awk -F"|" '
BEGIN{ f[2]=4; f[3]=5; f[5]=3; }
{for (i=1; i<=NF; i++) printf("%*s%s", f, $i, i==NF?"\n":FS);}
' input

set column widths on begin line as needed.

1 Like
awk '{$2=sprintf("%4s",$2); $3=sprintf("%5s",$3); $5=sprintf("%3s",$5)}1' FS=\| OFS=\| file
2 Likes