Monday, January 21, 2008

Substitute character by position - SED

This might be useful in situations where you are interested to replace a range of positions in a file with some value/string. Your input will be - line number of the file, character range position, and "replace with" string/value.


To replace character position 7-8 with "JK" in 2nd line of out.txt, here is the way using sed:

$ sed -r "2 ~ s/^(.{6})(.{2})/\1JK/" out.txt > out.txt.tmp; mv out.txt.tmp out.txt

Your range was : 7-8

Similar post:
- Replace text based on position using sed


Chinmaya said...

In VI editor this can be done i simple way.
:%s/orgText/NewTest/gc enter

gc at the end will ask for conformation, Current or Nexr or All.
:w fileName save the modification in new name. :q! will exit without any change.

Jadu Kumar Saikia said...

Hi Chinmaya,

First thanks for reading my post.

Well, the one you specified is a "replacing" way in vi, can be done from outside using sed:

sed 's/orgText/NewTest/' file

But if you read the post properly it tells about substitute based on character position range :-)

Thai said...

Hello Jadu,

For some reason the command you posted doesn't work for AIX implementation. It seems like AIX implementation doesn't understand the -r option of sed.

Jadu Kumar Saikia said...


try "man sed" to see if your AIX version of sed has any options for supporting extended regular expressions (-r). I will post any alternative solution if I find any. Thanks.


rahulsx said...

Hi Jadu,,

I have a file having lines like :

I need to replace the 8 numbers in between ie 9th character to 16th
using the matching :

0 --> H
1 --> W
2 --> E
3 --> V
4 --> T
5 --> M
6 --> F
7 --> B
8 --> Q
9 --> C
in all the lines of the file

© Jadu Saikia