Friday, May 30, 2008

Replace text based on position : sed


In one of my old post I discussed how to replace text from a particular position to another position (e.g. replace character position 7-8 with text "JK" )

Now something similar.

The input file is like this:


$ cat math.txt
4.569+12+4-9
2.3456-4.5+12
56+12+78+1234


Suppose I need to replace any '+' to '~' if it appears in 8 to 10 positions, and not all other '+'

i.e. Required output:

4.569+12~4-9
2.3456-4.5+12
56+12+78~1234


Awk code:


$ awk '{
x=substr($0,1,7)
y=substr($0,8,2)
gsub(/+/,"~",y)
z=substr($0,10)
print x y z
}' math.txt



Reference:
- awk substr function
- replace text from a particular position to a particular postilion.

No comments:

© Jadu Saikia www.UNIXCL.com