Santhosh
Santhosh

Reputation: 11824

How to replace a character before and after a match

I my file i have <br> tag. I want to replace any space before or after it using _ underscore character

How can i do this using sed or awk or perl.

Eg:

Note: I am using : because spaces are getting ignored with ` (tick marks)

: <br> : to be replaced with ____<br>___

: <br> : to be replaced with ______<br>___

: <br>: to be replaced with ______<br>

:<br> : to be replaced with <br>___

I tried

$ echo "test  test  <br>   test  test" | sed '/ *<br> */s/ /_/g' 
test__test__<br>___test__test

But i am expecting test test__<br>___test test

I tried @philippe answer.

Its working but i came up with another problem of spaces

I have tried

$ echo "for messages:<br>        # This" | perl -pe 's[(\s*<br>\s*)][$v=$1; $v =~ s/ /_/g; "$v"]ge'
for messages:<br>        # This

Why its not working.

If i delete the space and then manually insert the same spaces it works. What kind of spaces are those i dont know.

$ echo "for messages:<br>         # This" | perl -pe 's[(\s*<br>\s*)][$v=$1; $v =~ s/ /_/g; "$v"]ge'
for messages:<br>_________# This

Both the following sentenses look same but only one works. Can you tell me whats mysterious. You can copy paste in your terminal

"for messages:<br>        # This"  #NOT WORKIN
"for messages:<br>        # This"  #WORKING 

I copy pasted in sublime text editor to see what type of space characters are they

So \s*<br>\s* is working only with one type of spaces.

enter image description here

Also for the case not working

$ echo "for messages:<br>        # This" | od -a
0000000   f   o   r  sp   m   e   s   s   a   g   e   s   :   <   b   r
0000020   >   B  sp  sp   B  sp  sp   B  sp  sp   B  sp  sp   #  sp   T
0000040   h   i   s  nl

Upvotes: 2

Views: 101

Answers (1)

Philippe
Philippe

Reputation: 26697

Perl version:

echo "test  test  <br>   test  test" | perl -CSD -pe 's[\s*<br>\s*][$& =~ s/\s/_/gr]ge'

For the case which is not working, run this command and paster result :

echo "for messages:<br>        # This" | od -a

I have :

0000000   f   o   r  sp   m   e   s   s   a   g   e   s   :   <   b   r
0000020   >  sp  sp  sp  sp  sp  sp  sp  sp   #  sp   T   h   i   s  nl

Upvotes: 1

Related Questions