使用变量中的数据时如何在awk中使用单词边界
How to use word boundary in awk when using data from variable
我在 awk
中遇到单词边界问题
var="blue"
cat file
test
blue more
bluegrass not
yes red
more blue
fine blue, not
我只需要 blue
或多或少的行。
如果我这样做:
awk '/\<blue\>/' file
blue more
more blue
fine blue, not
我得到了我需要的输出(但这没有使用变量)。
但是如何用变量做到这一点?
以下是我的一些测试:
awk '[=13=]~"\<"test"\>"' test="$var" file
awk '[=13=]~/\</test/\>/' test="$var" file
awk '{a="\<"test"\>"} [=13=]~a' test="$var" file
所有这些都失败了。
只需要 awk
,因为这是更大测试的一部分。
更新。
似乎我的某些变量确实包含 +
唱。这阻止了 Ed
的解决方案
var="blue+"
cat file
test
blue+green more
bluegrass not
yes red
more blue+
fine blue+, not
awk -v test="$var" '[=16=]~"\<"test"\>"' file
blue+green more
more blue+
fine blue+, not
awk -v test="$var" '[=10=]~"\<"test"\>"' tfile
请记住,在正则表达式上下文中使用的字符串会被解析两次,一次是在读取时,一次是在执行时,因此如果需要转义,则需要将所有内容转义两次。
另请注意,\<
仅适用于 gawk。
根据更新的信息,您要搜索的文本可以包含 RE 元字符,您需要
- 转义可能出现在您文本中的所有 RE 元字符,或者
- 将其视为字符串
转义 RE 元字符是微不足道的,如果你只需要担心特定上下文中的几个,我相信你可以解决这个问题,但由于上下文敏感的性质,一般来说很难(不可能?)字符,所以我将专注于如何检测不属于较长 "word":
的字符串
awk -v test="$var" '
(s=index([=11=],test)) && # test exists and is neither
((s>1?substr([=11=],s-1,1):"") !~ /[[:alnum:]_]/) && # preceded by a word char nor
(substr([=11=],s+length(test),1) !~ /[[:alnum:]_]/) # succeeded by a word char
'
我在 awk
var="blue"
cat file
test
blue more
bluegrass not
yes red
more blue
fine blue, not
我只需要 blue
或多或少的行。
如果我这样做:
awk '/\<blue\>/' file
blue more
more blue
fine blue, not
我得到了我需要的输出(但这没有使用变量)。
但是如何用变量做到这一点?
以下是我的一些测试:
awk '[=13=]~"\<"test"\>"' test="$var" file
awk '[=13=]~/\</test/\>/' test="$var" file
awk '{a="\<"test"\>"} [=13=]~a' test="$var" file
所有这些都失败了。
只需要 awk
,因为这是更大测试的一部分。
更新。
似乎我的某些变量确实包含 +
唱。这阻止了 Ed
var="blue+"
cat file
test
blue+green more
bluegrass not
yes red
more blue+
fine blue+, not
awk -v test="$var" '[=16=]~"\<"test"\>"' file
blue+green more
more blue+
fine blue+, not
awk -v test="$var" '[=10=]~"\<"test"\>"' tfile
请记住,在正则表达式上下文中使用的字符串会被解析两次,一次是在读取时,一次是在执行时,因此如果需要转义,则需要将所有内容转义两次。
另请注意,\<
仅适用于 gawk。
根据更新的信息,您要搜索的文本可以包含 RE 元字符,您需要
- 转义可能出现在您文本中的所有 RE 元字符,或者
- 将其视为字符串
转义 RE 元字符是微不足道的,如果你只需要担心特定上下文中的几个,我相信你可以解决这个问题,但由于上下文敏感的性质,一般来说很难(不可能?)字符,所以我将专注于如何检测不属于较长 "word":
的字符串awk -v test="$var" '
(s=index([=11=],test)) && # test exists and is neither
((s>1?substr([=11=],s-1,1):"") !~ /[[:alnum:]_]/) && # preceded by a word char nor
(substr([=11=],s+length(test),1) !~ /[[:alnum:]_]/) # succeeded by a word char
'