Reputation: 5
How can I get sed to search a file from the bottom and find the first string it hits, then append after that? ie:
#file.test
Include sumeStuff1
Include sumeStuff2
Include sumeStuff3
Include sumeStuff4
Include sumeStuff5
Include sumeStuff6
Include sumeStuff7
Include sumeStuff8
Include SED_ENTRY
I know that I can do:
find -type f -name "file.test" | xargs sed -i "s/Include somestuff8/Include somestuff8\nInclude SED_ENTRY/g"
but, the problem is, I am building a script where I don't know what is the EXACT line is that is the last Include line, so I need to search from the bottom and then add a line after the last Include line.
Upvotes: 0
Views: 1242
Reputation: 10039
sed -n '1 h
$ {/^Include/ s/$/\
/ }
1! H
$ {x;s/\(.*Include [^[:cntrl:]]\{1,\}\)\(\n\)\(.*\)/\1\2Include SED_ENTRY\2\3/p;}' YourFile
Upvotes: 0
Reputation: 195179
try this one-liner:
awk 'NR==FNR{if(/^YOUR_PAT$/)n=NR;next}FNR==n{$0="SED_ENTRY"}7' file file
for your example, it would be:
awk 'NR==FNR{if(/^Include sumeStuff8$/)n=NR;next}FNR==n{$0="Include SED_ENTRY"}7' file file
Upvotes: 1
Reputation: 290025
With awk
:
$ tac a | awk 'BEGIN{p=1} /^Include/ && p==1 {print "Include SED_ENTRY"; print; p=0}1' | tac
Include sumeStuff1
Include sumeStuff2
Include sumeStuff3
Include sumeStuff4
Include sumeStuff5
Include sumeStuff6
Include sumeStuff7
Include sumeStuff8
Include sumeStuff8
Include SED_ENTRY
tac
prints a file the other way round.awk 'BEGIN{p=1} /^Include/ && p==1 {print "Include SED_ENTRY"; print; p=0}1'
adds the "Include SED_ENTRY"
before the first line starting with "Include"
and flags it so that the line is not printed again.tac
finally reverses the output.Upvotes: 0