Padding with zeros.

Hi Friends,

I would like to left pad with "0's" on first column say (width six)
I have a large file with the format:

FILE:

1: ALFRED 84378 NY
8385: JAMES 88385 FL
323: SMITH 00850 TX

My output needs to be like:

000001: ALFRED 84378 NY
008385: JAMES 88385 FL
000323: SMITH 00850 TX

Thanks in advance for your help

#! /bin/ksh

typeset -RZ 6 code

while IFS=':' read first rest
do
    code=${first}
    echo "${code}: ${rest}"
done < input.txt
while IFS=':' read first rest
do
    printf "%06d:%s\n" $first "$rest"
done< file

Another way:

awk -F: '{ printf "%06d: %s\n", $1,$2 }' input.txt

Hi all,

Referencing the awk statement here

awk -F: '{ printf "%06d: %s\n", $1,$2 }' input.txt

, I want to apply this concept to the 5th field, where I am padding 6 leading zeroes, and the rest of my fields stay the same. I tried the following:

awk -F, '{ printf "%06d, %s\n", $6,$7 }' test1.csv > test2.csv

but it won't output my first five fields or fields after the 6th field.

Please advise. Thanks much!
Lim

 echo "1 2 3 4 5 6 7 8 9" | awk '{ $6=sprintf("%06s", $6); print $0}'
1 2 3 4 5 000006 7 8 9

Thanks Jim. This looks like it would do the trick. I can't get it working with my code though. I started using this:

while IFS=',' read first rest
do
  printf "%07d,%s\n" $first "$rest" >> newfile.csv
done< file.csv

which will pad the first field. But I would like to pad the second field. How do I get the code above to pad the second? Thanks much!

Here's the input file:
"100","100","ABC"
"100","200","ABC"
"100","300","ABC"

Here's the desired output:
"100","0000100","ABC"
"100","0000200","ABC"
"100","0000300","ABC"

If you have exactly 3 fields in the file, then:

$
$ cat file.csv
"100","100","ABC"
"100","200","ABC"
"100","300","ABC"
$
$ # awk
$ awk -F, '{gsub(/"/,""); printf("\"%s\",\"%07s\",\"%s\"\n",$1,$2,$3)}' file.csv
"100","0000100","ABC"
"100","0000200","ABC"
"100","0000300","ABC"
$
$ # or perl
$ perl -ne '{chomp; split /","/; printf("%s\",\"%07s\",\"%s\n",$_[0],$_[1],$_[2])}' file.csv
"100","0000100","ABC"
"100","0000200","ABC"
"100","0000300","ABC"
$

tyler_durden

Thanks Tyler, this does the trick!

if you have Python

#!/usr/bin/env python
import csv
filename = "file"
reader = csv.reader(open(filename))
writer = csv.writer( open("newfile.csv","wb"), quoting=csv.QUOTE_ALL)
for row in reader: 
    writer.writerow(row)

output

# ./test.py
# more newfile.csv
"100","0000100","ABC"
"100","0000200","ABC"
"100","0000300","ABC"

I don't have python, but thanks!