Re: Script to search an input file, insert a line and then update the file
- From: "Bill Pursell" <bill.pursell@xxxxxxxxx>
- Date: 15 Oct 2006 10:45:34 -0700
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)
.
- Follow-Ups:
- Re: Script to search an input file, insert a line and then update the file
- From: Michal Nazarewicz
- Re: Script to search an input file, insert a line and then update the file
- References:
- Script to search an input file, insert a line and then update the file
- From: hiddenmarkov
- Script to search an input file, insert a line and then update the file
- Prev by Date: Re: Signal catch code; can it make kernel commands
- Next by Date: strptime() get segment corruption in linux
- Previous by thread: Re: Script to search an input file, insert a line and then update the file
- Next by thread: Re: Script to search an input file, insert a line and then update the file
- Index(es):
Relevant Pages
|
|