GNU awk: accessing captured groups in replacement text

后端 未结 2 723
走了就别回头了
走了就别回头了 2020-12-15 16:10

This seems like it should be dirt simple, but the awk gensub/gsub/sub behavior has always been unclear to me, and now I just can\'t get it to do what the documentation says

相关标签:
2条回答
  • 2020-12-15 16:16

    Per the gawk manual

    gensub provides an additional feature that is not available in sub or gsub: the ability to specify components of a regexp in the replacement text. This is done by using parentheses in the regexp to mark the components and then specifying ‘\N’ in the replacement text, where N is a digit from 1 to 9.

    You must use gensub, you must specify "g", and you must grab the result of gensub, since it does not modify in-place.

    awk '{ r = gensub(/a(b*)c/, "Here are bees: \\1", "g"); print r; }'
    
    0 讨论(0)
  • 2020-12-15 16:20
    echo abbc | awk '{ print gensub(/a(b*)c/, "Here are bees: \\1", "g", $1);}'
    

    See manual here to see the difference between gsub and gensub

    0 讨论(0)
提交回复
热议问题