KeithSmith
KeithSmith

Reputation: 774

How to replace the first n occurrences of one character with another using sed

I have file with lines of text that have values that are zero filled. I would like to replace all the leading zeros with spaces, but only for up to 7 times.

00000002:   <text>

Change the above to the following

       2:   <text>

I have the sed script

s/^0/ /;: loop s/ 0/  /;t loop

It replaces ALL the zeros.

The line

00000000:   <text>

is changed to

        :   <text>

I would like

       0:   <text>

and this would occur if the sed loop was able to be stopped after 6 loops.

How do I change the sed script to stop after 6 (n) loops.

Yes, I could brute force it and put in 6 versions of s/ 0/ /.

Upvotes: 2

Views: 1852

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/.*/ & /;s/\([²³]\)/\1o/g
   s/\([^[:digit:]]\)\(0\{1,7\}\)\([[:digit:]]\)/\1²\2³\3/g
: space
   s/²\( *\)0\(0*\)³/²\1 \2³/g
   t space
   s/²\( *\)³/\1/g
   s/\([²³]\)o/\1/;s/ \(.*\) /\1/'

The {1,7} specify the number of leading 0 you want to replace.

It replace all 0 of all number of the line. If it is only for the first number found

replace second line by this:

s/^\([^[:digit:]]*\)\(0\{1,7\}\)\([[:digit:]]\)/\1²\2³\3/

Upvotes: 0

potong
potong

Reputation: 58483

This might work for you (GNU sed):

sed -r 's/[^0]/\n&/;h;y/0/ /;G;s/\n.*\n//;s/ :/0:/' file

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247012

Perl is handy for this:

$ printf "%08d: blah\n" {0..12..4}
00000000: blah
00000004: blah
00000008: blah
00000012: blah
$ printf "%08d: blah\n" {0..12..4} | perl -pe 's/^0+(?=\d+:)/ " " x length($&) /e'
       0: blah
       4: blah
       8: blah
      12: blah

Upvotes: 2

janos
janos

Reputation: 124714

Well, this is probably cheating, and I'm not sure it will work for all of your corner cases:

sed 's/^0/ /;s/0:/x:/;: loop s/ 0/  /;t loop;s/x:/0:/'

Actually, better yet:

sed 's/^0/ /;: loop s/ 0/  /;t loop;s/ :/0:/'

Upvotes: 2

Related Questions