LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   How to use sed replace matching string of line contents at fixed position (https://www.linuxquestions.org/questions/linux-general-1/how-to-use-sed-replace-matching-string-of-line-contents-at-fixed-position-4175470987/)

lwsunny 07-26-2013 06:41 AM

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

Ser Olmy 07-26-2013 07:16 AM

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/'

lwsunny 07-26-2013 07:23 AM

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...

Ser Olmy 07-26-2013 07:35 AM

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
  [... process $x here and write the results to another file ...]
done < input_file

A quick search of the LQ forums should turn up a few examples.

druuna 07-26-2013 08:03 AM

@lwsunny: These bash related links might come in handy:

danielbmartin 07-31-2013 08:50 PM

Quote:

Originally Posted by lwsunny (Post 4997169)
i am new to linux script, how can i loop each line of the input file, then output the replace one to another file...

No need for an explicit loop. You may convert an entire input file with a single line of code.

Using sed, as coded by Ser Olmy:
Code:

sed 's/^\(.\{3\}\)ABC\(.\{3\}\).\{3\}\(.*\)/\1ABC\2DEF\3/' $InFile >$OutFile
Using awk, as coded by yours truly:
Code:

awk 'BEGIN{FS=OFS=""} {if (substr($0,4,3)=="ABC") {$10="DEF";$11=$12=""}}1' $InFile >$OutFile
Daniel B. Martin


All times are GMT -5. The time now is 05:22 PM.