0

I have a RHEL kickstart file as below with multiple %post ... %end sections in it having many lines of Python code in between them.

%post
.....
.....
%end
%post
.....
.....
%end
%post
.....
.....
%end

I am trying to insert a new line with some data just before (above) the 2nd occurrence of search pattern "%end" from last (EOF). Any hints/input is really appreciated.

closed as unclear what you're asking by Jeff Schaller, Jesse_b, roaima, G-Man Says 'Reinstate Monica', user34720 May 10 '18 at 17:05

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • how about Unix command-line tools? – RomanPerekhrest May 9 '18 at 13:20
  • @don_crissti I tried with findall() but gives list of the patterns from that I have used -2 index to retrieve the 2nd occurrence of pattern from last, but unable to fetch the line no above this 2nd occurrence of the pattern – Ibrahim Quraish May 9 '18 at 14:24
  • @RomanPerekhrest, I used the code something like, tac file | awk -v n=0 '/%end/ {n++}; if (n==3) {print FNR-1}' – Ibrahim Quraish May 9 '18 at 14:26
  • What's the relevance of Python in the title? – roaima May 9 '18 at 22:21
  • @roaima I have to do it via Python to insert some python code into this target kickstart file which contains python code. I am thinking of using shell script is to be imbibed in Python's subprocess.Popen() – Ibrahim Quraish May 10 '18 at 6:08
2

Python snippet that inserts text spam at the last position in the second-to-last %post..%end block:

with open('input') as fp:
    lines = fp.readlines()

locs = [i for i, val in enumerate(lines) if val == '%end\n']
lines.insert(locs[-2], 'spam' + '\n')

with open('input', 'w') as fp:
    fp.write(''.join(lines))
1

To insert "some data" before next to last pattern line.
grep + awk solution:

awk -v n="$(($(grep -c '^%end' inputfile) - 1))" \
'/^%end/{ if (++cnt == n) print "some data" }1' inputfile

The output:

%post
.....
.....
%end
%post
.....
.....
some data
%end
%post
.....
.....
%end

Not the answer you're looking for? Browse other questions tagged or ask your own question.