Using awk, how we can add text at the bottom, only if a certain pattern was not found in the file?

This is not working:

awk '{if ($0 !~ /pattern/) {print}; END {print "someText"}}' file

The file is small, less than 1MB.

2 Answers 2


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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .