gsub 替换翻译不起作用
gsub for substituting translations not working
我有一个字典 dict
,其中的记录由“:”分隔,数据字段由新行分隔,例如:
:one
1
:two
2
:three
3
:four
4
现在我想要 awk 替换 input
中每条记录的所有出现
文件,例如
onetwotwotwoone
two
threetwoone
four
我的第一个 awk 脚本看起来像这样并且工作得很好:
BEGIN { RS = ":" ; FS = "\n"}
NR == FNR {
rep[] =
next
}
{
for (key in rep)
grub(key,rep[key])
print
}
给我:
12221
2
321
4
不幸的是,另一个 dict 文件包含一些正则表达式使用的字符,因此我必须在我的脚本中替换转义字符。通过将 key 和 rep[key] 移动到一个字符串中(然后可以解析为转义字符),脚本将只替换字典中的第二条记录。为什么?以及如何解决?
这是脚本的当前第二部分:
{
for (key in rep)
orig=key
trans=rep[key]
gsub(/[\]\[^$.*?+{}\()|]/, "\\&", orig)
gsub(orig,trans)
print
}
所有脚本都是 运行 awk -f translate.awk dict input
提前致谢!
没关系问....
只是少了一些括号...?!
{
for (key in rep)
{
orig=key
trans=rep[key]
gsub(/[\]\[^$.*?+{}\()|]/, "\\&", orig)
gsub(orig,trans)
}
print
}
很有魅力。
您的根本问题是在不需要的正则表达式和反向引用上下文中使用字符串,然后尝试转义字符串中的元字符以禁用您通过在这些上下文中使用它们而启用的字符。如果你想要字符串,在字符串上下文中使用它们,仅此而已。
你不会想要这个:
gsub(regexp,backreference-enabled-string)
你想要更像这样的东西:
index(...,string) substr(string)
我想这就是你想要做的:
$ cat tst.awk
BEGIN { FS = ":" }
NR == FNR {
if ( NR%2 ) {
key =
}
else {
rep[key] = [=12=]
}
next
}
{
for ( key in rep ) {
head = ""
tail = [=12=]
while ( start = index(tail,key) ) {
head = head substr(tail,1,start-1) rep[key]
tail = substr(tail,start+length(key))
}
[=12=] = head tail
}
print
}
$ awk -f tst.awk dict file
12221
2
321
4
我有一个字典 dict
,其中的记录由“:”分隔,数据字段由新行分隔,例如:
:one
1
:two
2
:three
3
:four
4
现在我想要 awk 替换 input
中每条记录的所有出现
文件,例如
onetwotwotwoone
two
threetwoone
four
我的第一个 awk 脚本看起来像这样并且工作得很好:
BEGIN { RS = ":" ; FS = "\n"}
NR == FNR {
rep[] =
next
}
{
for (key in rep)
grub(key,rep[key])
print
}
给我:
12221
2
321
4
不幸的是,另一个 dict 文件包含一些正则表达式使用的字符,因此我必须在我的脚本中替换转义字符。通过将 key 和 rep[key] 移动到一个字符串中(然后可以解析为转义字符),脚本将只替换字典中的第二条记录。为什么?以及如何解决?
这是脚本的当前第二部分:
{
for (key in rep)
orig=key
trans=rep[key]
gsub(/[\]\[^$.*?+{}\()|]/, "\\&", orig)
gsub(orig,trans)
print
}
所有脚本都是 运行 awk -f translate.awk dict input
提前致谢!
没关系问.... 只是少了一些括号...?!
{
for (key in rep)
{
orig=key
trans=rep[key]
gsub(/[\]\[^$.*?+{}\()|]/, "\\&", orig)
gsub(orig,trans)
}
print
}
很有魅力。
您的根本问题是在不需要的正则表达式和反向引用上下文中使用字符串,然后尝试转义字符串中的元字符以禁用您通过在这些上下文中使用它们而启用的字符。如果你想要字符串,在字符串上下文中使用它们,仅此而已。
你不会想要这个:
gsub(regexp,backreference-enabled-string)
你想要更像这样的东西:
index(...,string) substr(string)
我想这就是你想要做的:
$ cat tst.awk
BEGIN { FS = ":" }
NR == FNR {
if ( NR%2 ) {
key =
}
else {
rep[key] = [=12=]
}
next
}
{
for ( key in rep ) {
head = ""
tail = [=12=]
while ( start = index(tail,key) ) {
head = head substr(tail,1,start-1) rep[key]
tail = substr(tail,start+length(key))
}
[=12=] = head tail
}
print
}
$ awk -f tst.awk dict file
12221
2
321
4