Given a regular expression and a replacement string, how can I use awk to implement the following:

  • if a line contains no match, does nothing;
  • if a line contains more than one matches, replace the last match with the replacement string, in the sense of the last match which would be substituted by gsub();
  • if a line contains exactly one match, replace the match with the replacement string.

For example, see " unexpected character '\'" in gawk


  • 6
    Why do you need awk? sed 's/\(.*\)regex/\1replacement/' should be enough. – muru Jul 18 '17 at 8:12
  • In awk you could try something like: awk '$NF ~ /pattern/{gsub($NF,"replacestring")}1' somefile. Awk uses $NF to indicate the last field in a row. – Valentin Bajrami Jul 18 '17 at 8:24
  • 2
    show the input sample, do some practice – RomanPerekhrest Jul 18 '17 at 8:29
  • 2
    @val0x00ff Last field does not imply the last regex location. – user218374 Jul 18 '17 at 12:06
  • 2
    Please edit your question to show what you have tried so far. Without that information, it's hard to give advice on the specific problem. You should also read How to Ask. – Toby Speight Jul 18 '17 at 17:30

Use your pattern as awk's field separator '-F"PATTERN' and add a condition if number of feilds >2 (NF>2) means your pattern is only accurate one time else it's =NF-1 times, then print all feilds except last one when you set the FS=OFS="PATTERN" again then print the "replaceString" and end print last field, no gsub needed.

hope you get the idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.