gpt4 book ai didi

awk - GNU Awk 中的强类型正则表达式常量如何工作?

转载 作者:行者123 更新时间:2023-12-03 18:57:18 24 4
gpt4 key购买 nike

强类型正则表达式常量是 GNU Awk 的一个方便的工具。它记录在 GNU Awk User's Guide -> 6.1.2.2 Strongly Typed Regexp Constants 中在那里你可以找到有趣的例子。
从阅读到评论到 an answer我编了一些例子来说明这些:

$ cat file
he;llo
ho
are
you;
$ gawk -v patt='@/;/' '$0 ~ patt' file # it prints those lines containing ";"
he;llo
you;
在这种情况下,我们传递模式“;”与 @/;/所以它打印所有包含“;”的行在他们之中。
现在我想更进一步,动态设置这个参数。例如,将其放在要读取的文件的第一行:
$ cat file
;
line2: hello;how
line3: are|you?
line4: i am;fine
但是,我无法将模式设置为 $0 中包含的字符串,我尝试了多种方法:
gawk 'NR==1 {f=@""$0; next} $0 ~ f' file
gawk 'NR==1 {f=@$0; next} $0 ~ f' file
但它们都返回一个语法错误:
gawk: cmd. line:1: NR==1 {f=@$0; next} $0 ~ f
gawk: cmd. line:1: ^ syntax error
在这种情况下, ”;”被设置为匹配的模式,我希望它处理第 2 行的正则表达式,从而匹配第 2 行和第 4 行,就好像我们会做 gawk 'NR==1 {f=@/;/; next} $0 ~ f' .但是,我无法动态设置强类型正则表达式常量。
有没有办法这样做?

最佳答案

wrt I cannot set the strongly typed regexp constant dynamically - 你可以用该语句中的任何其他字符串替换“强类型正则表达式”,它仍然是正确的,因为根据定义你不能动态设置常量,“常量”和“动态”是互斥的。
强类型正则表达式常量主要用于将文字正则表达式传递给用户定义的函数(使用常规正则表达式常量无法做到这一点):

$ awk 'function foo(x){print x, typeof(x)} BEGIN{foo(/bar/)}'
awk: cmd. line:1: warning: regexp constant for parameter #1 yields boolean value
0 number

$ awk 'function foo(x){print x, typeof(x)} BEGIN{foo("bar")}'
bar string

$ awk 'function foo(x){print x, typeof(x)} BEGIN{foo(@/bar/)}'
bar regexp
所以你不需要像动态正则表达式那样额外的转义层,因为 awk 在使用它之前不必先将表达式转换为正则表达式:
$ echo 'a.b a#b' | awk 'BEGIN{old="a\.b"; new="_"} {gsub(old,new)} 1'
awk: cmd. line:1: warning: escape sequence `\.' treated as plain `.'
_ _

$ echo 'a.b a#b' | awk 'BEGIN{old="a\\.b"; new="_"} {gsub(old,new)} 1'
_ a#b

$ echo 'a.b a#b' | awk 'BEGIN{old=@/a\.b/; new="_"} {gsub(old,new)} 1'
_ a#b
您尝试对问题中的示例执行的是动态设置正则表达式,因此需要一个动态的(即指定为字符串的)而不是常量正则表达式:
$ awk 'NR==1{f=$0; next} $0 ~ f' file
line2: hello;how
line4: i am;fine

关于awk - GNU Awk 中的强类型正则表达式常量如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65617751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com