Operating System - HP-UX
1752754 Members
4591 Online
108789 Solutions
New Discussion

Adding leading zeroes to text in a file

 
SOLVED
Go to solution
ecbakken
Occasional Contributor

Adding leading zeroes to text in a file

Hello all,

 

I'm creating a tag file and need to fill in a 4 digit field with a number and leading zeros. For example, I would need to turn this:

 

74 

5

143

 

into this:

 

0074

0005

0143

 

Is this possible? Thanks,

 

-Eric

 

 

4 REPLIES 4
Steven Schweda
Honored Contributor
Solution

Re: Adding leading zeroes to text in a file

> I'm creating a tag file [...]

 

   Tells me approximately nothing.  I'll assume a shell script to
process an existing file.

 

   Not very efficient, but...

 

$ cat nlz.txt
74
5
143

$ (  while read line ; do echo "0000$line" | sed -e 's/.*\(....\)/\1/' ; done ) < nlz.txt
0074
0005
0143

ecbakken
Occasional Contributor

Re: Adding leading zeroes to text in a file

I'm sorry for the lack of information and I commend your assumption skills. This is exactly what I needed. Thank you.
James R. Ferguson
Acclaimed Contributor

Re: Adding leading zeroes to text in a file

Hi:

 

Another way:

 

# while read line;do printf "%04d\n" $line;done < file


Regards!

 

...JRF...

Dennis Handly
Acclaimed Contributor

Re: Adding leading zeroes to text in a file

If you want leading zeros in your shell variables, you can use:

typeset -Z4 variable=0

echo $variable

0000

 

In your case you can read your file and assign to "variable" and then print it out.

for variable in $(< file); do

   echo $variable

done