linux - Add a prefix to beginning of each line depending on its size -


i have file postal codes , city names :

1234  foo 4321  foobar 64324 foofoobar 92001 bar 

with \t between numbers , city name. add prefix 0 each line 4 numbers, using sed or shell script

01234 foo 04321 foobar 64324 foofoobar 92001 bar 

thanks help.

assuming postcodes numeric, can use printf command in awk task, per following transcript (the v characters there show tab stops are):

pax> printf "v\tv\tv\n" ; cat infile v       v       v 1234    rio     xyz 4321    munich  abc 64324   perth   def 92001   paris   qqq  pax> awk 'begin {ofs = "\t"} {arg1 = $1; $1 = ""; printf "%05d%s\n", arg1, $0}' infile 01234   rio     xyz 04321   munich  abc 64324   perth   def 92001   paris   qqq 

the awk command first extracts and removes first argument(a) each line, formats along changed line.

you'll notice i've set output field separator tab character since appears you're using. may not necessary, depends on how closely want output data match input.


(a) technically sets empty string, argument still exists. that's why there's no tab needed between %05d , %s in format string, since tab still there.


Comments