append a word to the end of a line in txt file
You could use the following awk
program:
awk -v s=" OK" '/OK$/ { print; } !/OK$/ { print $0 s; s=""; }'
It works like this:
/OK$/ { print; }
prints out any line ending in OK
as is, whereas
!/OK$/ { print $0 s; s=""; }
prints out any line not ending in OK
with the value of variable s
appended.
Variable s
initially is the string ' OK'
. It changes to the empty string after the first encounter of a line not ending in OK
.
Update
Even more concisely:
awk -v s=" OK" '!/OK$/ { print $0 s; s=""; } /OK$/'
eliminates the { print; }
action for the /OK$/
condition, as { print; }
is the default action.
Correction
Looking at the question again, it does not say the OK
should be added to the first line not having OK
, but instead to the first line not having an OK
which follows a line that does have an OK
. So, we must keep a variable, c
that flags that at least one OK
line has been seen, and a variable d
that flags that we are done:
awk ' /OK$/ { if (!d) c=1; }
!/OK$/ { if (c) d=1; }
c && d { s=" OK"; c=0; }
{ print $0 s; s=""; }'