我对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 '$0~"\<"test"\>"' test="$var" file
awk '$0~/\</test/\>/' test="$var" file
awk '{a="\<"test"\>"} $0~a' test="$var" file所有这些都失败了。
只需要awk,因为这是更大的测试的一部分。
更新。
我的一些变量似乎确实包含了一个+ sing。这阻止了Ed的解决方案
var="blue+"cat file
test
blue+green more
bluegrass not
yes red
more blue+
fine blue+, notawk -v test="$var" '$0~"\\<"test"\\>"' file
blue+green more
more blue+
fine blue+, not发布于 2015-02-24 20:00:10
awk -v test="$var" '$0~"\\<"test"\\>"' tfile记住,在regexp上下文中使用的字符串会被解析两次,一次是在读取时,另一次是在执行时,所以如果需要转义,则需要对所有内容进行两次转义。
还请注意,\<是纯gawk的。
给定要搜索的文本可以包含所需的RE元字符的更新信息。
如果你在特定的环境中只有几个人需要担心,而我相信你能弄清楚这一点,那么逃避RE元元就很简单了,但是很难(不可能?)一般来说,由于字符的上下文敏感性质,所以我将重点讨论如何检测不是较长的“word”的一部分的字符串:
awk -v test="$var" '
(s=index($0,test)) && # test exists and is neither
((s>1?substr($0,s-1,1):"") !~ /[[:alnum:]_]/) && # preceded by a word char nor
(substr($0,s+length(test),1) !~ /[[:alnum:]_]/) # succeeded by a word char
'https://stackoverflow.com/questions/28705084
复制相似问题