Search code examples
bashshellawkksh

how to add zero to single digit date in a date field in shell


I have data like the below

1213231421312131|USER|21121|1231412|XEM|NAME|NAME|||5072020|2313||||NY|2131|||99|E|||ver.01
6454242352352352|USER|13131|7342422|XEM|NAME|NAME|||13032001|1231||||TX|7312|||11|E|||ver.01
5131242515111233|USER|21212|2314413|XEM|NAME|NAME|||2101979|1231||||TX|7312|||11|E|||ver.01
2341313412341123|USER|62422|1124242|XEM|NAME|NAME|||23111979|1231||||TX|7312|||11|E|||ver.01

I need data as below

1213231421312131|USER|21121|1231412|XEM|NAME|NAME|||05072020|2313||||NY|2131|||99|E|||ver.01
6454242352352352|USER|13131|7342422|XEM|NAME|NAME|||13032001|1231||||TX|7312|||11|E|||ver.01
5131242515111233|USER|21212|2314413|XEM|NAME|NAME|||02101979|1231||||TX|7312|||11|E|||ver.01
2341313412341123|USER|62422|1124242|XEM|NAME|NAME|||23111979|1231||||TX|7312|||11|E|||ver.01

So filed 10 is a date column, i would like to add zero to date... 7 digit to 8 digit. I have used the below command, but that command replacing Pipe symbol to space.

awk -F "|" '{$10 = sprintf("%08d", $10); print}' <fileName>

Please help me with this request

thank you Yum


Solution

  • awk has an input field separator and an output field separator. The print command uses the latter. So to keep the | symbols, set the output field separator OFS too:

    awk -F\| -v OFS=\| '{$10 = sprintf("%08d", $10); print}' yourFile
    

    Or with numfmt from GNU coreutils (preinstalled on most Linux systems)

    numfmt -d\| --field 10 --format %08f < yourFile