Re: Script to search an input file, insert a line and then update the file



hiddenmarkov@xxxxxxxxx wrote:
Hi,
Could any expert out there give me a hint / command used or even a
sample code in writing a script which can perform the function in the
subject line, i.e. read in a file, search for specific string, if the
string is found, insert a line and then close the file? Any suggestion
is appreciated.

NewB.

Rainer's suggestion of ed is cool:

$ echo -e -n '/pattern/a\ninserted text\n.\nw\nq\n' | ed foo

Should insert "inserted test" after the first occurence of "pattern" in
the file foo, but I don't even know how to easily extend it to
capture all instances of the pattern. Also, it emits an error
if the pattern doesn't appear in the file. Here's a python snippet
that seems to work:

#!/usr/bin/env python

import sys, re

f = file(sys.argv[2], 'r')
pattern = sys.argv[1]
buf = []

for line in f.xreadlines():
buf.append(line)
if re.match(pattern, line):
buf.append("Added line\n")

f.close()
f = file(sys.argv[2], 'w')
for line in buf:
f.write(line)

.



Relevant Pages

  • Re: [RFC] Extending kbuild syntax
    ... The second is the more controversial suggestion. ... The pattern varies over this theme. ... To better express how to use it I have tried to update a few Makefiles ...
    (Linux-Kernel)
  • Re: How to improve performance of regular expression pattern matching
    ... did you try Ed's suggestion to create one regular ... > expression for all of the array elements? ... The reason I used an array of patterns rather than a single pattern ...
    (comp.unix.shell)
  • Re: Script to search an input file, insert a line and then update the file
    ... subject line, i.e. read in a file, search for specific string, if the ... Rainer's suggestion of ed is cool: ... the file foo, but I don't even know how to easily extend it to ... if the pattern doesn't appear in the file. ...
    (comp.unix.programmer)
  • Re: Data conversion
    ... My next suggestion would be the same as Carsten's. ... If you can't spot any ... pattern by looking at the data, you may have to use whatever export ... Install a printer on your system which "prints" ...
    (microsoft.public.fox.helpwanted)