Awk: if pattern not found add some text at the end of file

another awk approch which is about a bit faster on big file size that exits as soon as pattern found and append something to the file if pattern was not found.

awk '/pattern/{found=1; exit}; END{ if(!found) print "append" >>FILENAME }' infile

or alternatively using grep:

<infile grep -q pattern || echo 'appending...' >>infile

The following should work:

awk '/pattern/ {found=1} {print} END{if (!found) print "someText"}' file

This will a priori print the entire file ({print} rule without conditions) and at that time look for the pattern. If it is found, it sets a flag ( {found=1} with the condition /pattern/, which is equivalent to $0 ~ /pattern/). If that flag is not set at end-of-file, the "someText" will be printed.

You can either redirect the output to a new file, as in

awk ' <see above> ' file > newfile

or, if you have a newer version of GNU awk, use the "inplace" editing function (with care!):

awk -i inplace ' <see above> ' file