Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing leading "0" with blanks 3

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi folks,

I need to automatically format several strings in a way that every leading "0" is being replaced by a " " (blank)...

Any idea how I could do this ?

The strings could look like this:

Code:
000000000028302
000000028372022
000018000290000

And they're supposed to look like this after being formatted:

Code:
          28302
       28372022
    18000290000

It is important to have the blanks because each string is supposed to be a 15 character field that's being read by another programm ...

Regards
Thomas
 
Code:
sed -e 's!^0! !;: loop' -e 's! 0!  !;t loop' /path/to/input >output

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
You're a genius !!!!

Thanks a lot !

I have no idea what this does, but it works ... ;-)
 
Without reading the man page, I'd hazard this guess:

first replace one leading zero with a space

then in the input line, loop to replace all occurrences of ' 0' with ' '

To understand looping/branching in sed programs fully (and write one myself) I *would* need reading the man page though.

Side remark: what if the leading zeroes aren't in the first field of the file?


HTH,

p5wizard
 
Could one get clever with an awk statement that used printf to format the output? Something like
Code:
awk '{printf "%15d\n", $1}' input_file
This could be modified to cover p5wizard's question about formatting fields other than the first.


On the internet no one knows you're a dog

Columb Healy
 
rephrase:

Side remark: what if the leading zeroes aren't in the first field of the file [red]and fields are not separated by spaces (tabs, commas, semicolons)[/red]?

for commas:

[tt]sed -e 's!^0! !; s!,0!, !g;: loop' -e 's! 0! !;t loop' /path/to/input >output[/tt]


HTH,

p5wizard
 
Another option ...

$ cat /tmp/xxx
0001234
0001235
0001234
0001234
0987651
0000043

$ for v in $(</tmp/xxx)
do
typeset -LZ7 v;typeset -R7 v
echo "$v"
done
1234
1235
1234
1234
987651
43
 
For a little variety:

perl -lne 's/^(0+)/" " x length($1)/e;print' < /tmp/xxx



Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top