Given a file like this:
a
b
a
b
I\'d like to be able to use sed
to replace just the last line that contains an instance of \"a
awk
-only solution:
awk '/a/{printf "%s", all; all=$0"\n"; next}{all=all $0"\n"} END {sub(/^[^\n]*/,"c",all); printf "%s", all}' file
Explanation:
a
, all lines between the previous a
up to (not including) current a
(i.e. the content stored in the variable all
) is printeda
, it gets appended to the variable all
.a
would not be able to get its all
content printed, so you manually print it out in the END
block. Before that though, you can substitute the line matching a
with whatever you desire.Here is a way with only using awk
:
awk '{a[NR]=$1}END{x=NR;cnt=1;while(x>0){a[x]=((a[x]=="a"&&--cnt==0)?"c <===":a[x]);x--};for(i=1;i<=NR;i++)print a[i]}' file
$ cat f
a
b
a
b
f
s
f
e
a
v
$ awk '{a[NR]=$1}END{x=NR;cnt=1;while(x>0){a[x]=((a[x]=="a"&&--cnt==0)?"c <===":a[x]);x--};for(i=1;i<=NR;i++)print a[i]}' f
a
b
a
b
f
s
f
e
c <===
v