How to use sed replace matching string of line contents at fixed position
hi all, i need to loop each lines of a file, and look up if there is a matching word at specific position, eg. at position 6= ABC;
then replace the words at position 10 with DEF; thanks for any help!! e.g. input_file.txt 123ABC789JKL123 123ABC789MNL123 123FGH789PQR123 output_file as: output.txt 123ABC789DEF123 123ABC789DEF123 123FGH789PQR123 |
Basically, you search for the following pattern (pseudo-code):
<start of line>(<X random characters>)ABC(<y random characters>)<3 random characters>(<rest of line>)The parts in parentheses must be stored for backreferencing. Now replace with: (backref 1)ABC(backref 2)DEF(backref 3)The following sed command will replace characters 10-12 with "DEF" in any string where characters 4-6 are "ABC": Code:
sed 's/^\(.\{3\}\)ABC\(.\{3\}\).\{3\}\(.*\)/\1ABC\2DEF\3/' |
thanks for quick reply!
i am new to linux script, how can i loop each line of the input file, then output the replace one to another file... |
That's a very common question, and it has been answered here on LQ quite a few times.
Most would recommend using a while loop and input redirection: Code:
while read x ; do |
@lwsunny: These bash related links might come in handy:
|
Quote:
Using sed, as coded by Ser Olmy: Code:
sed 's/^\(.\{3\}\)ABC\(.\{3\}\).\{3\}\(.*\)/\1ABC\2DEF\3/' $InFile >$OutFile Code:
awk 'BEGIN{FS=OFS=""} {if (substr($0,4,3)=="ABC") {$10="DEF";$11=$12=""}}1' $InFile >$OutFile |
All times are GMT -5. The time now is 05:22 PM. |