2

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

Thanks.

13
  • 6
    Why do you need awk? sed 's/\(.*\)regex/\1replacement/' should be enough.
    – muru
    Jul 18, 2017 at 8:12
  • 2
    show the input sample, do some practice Jul 18, 2017 at 8:29
  • 3
    @val0x00ff Last field does not imply the last regex location.
    – user218374
    Jul 18, 2017 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. Jul 18, 2017 at 17:30
  • 1
    @muru your suggestion would fail if the RE started with any variable length atom, such as x{3,6} because the greedy (.*) could eat up to three of the x characters and still be part of an overall valid RE.
    – roaima
    Jul 18, 2017 at 22:39

1 Answer 1

2

Not using gsub() but use your Pattern as the field separator for FS & OFS, then print all the fields except the last two with the OFS intact; next print the second last field followed by the "REPLACEMENT-STRING" and then the last field.

awk 'BEGIN{ FS=OFS="pat" }
      NF>1{ for(i=1; i<NF-1; i++) printf "%s", $i OFS;
            printf "%s\n", $i "REPLACEMENT-STRING" $NF; next
}1' infile

Sample input:

        pat 1 pat2 patt 3 pat 4
 pat
patt pat
pa t

Output:

        pat 1 pat2 patt 3 REPLACEMENT-STRING 4
 REPLACEMENT-STRING
patt REPLACEMENT-STRING
pa t

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.