Search code examples
regexstringawkprepend

Prepend string to line if line ends in keyword


Assume a multi-line text file (file) and the keyword bar.

> cat file
foo bar baz
foo bar quux
foo quux bar

Each line that ends with the keyword shall be prepended with the string Hello; each line that does not shall be printed as is.

> cat file | sought_command
foo bar baz
foo bar quux
Hello foo quux bar

I believe that this can be done via awk (something along the lines of awk '$ ~ /bar/ {print "Hello", $0}'), but I cannot come up with the correct code and would appreciate suggestions.


Solution

  • You are almost on the right track using Awk, just use the regex anchor $ to mark the end the line, and append the string as needed,

    awk '$NF == "bar"{$0="Hello"FS$0}1' file
    

    This will append string only to those lines having keyword in the last.