[英]word boundaries to handle dot sign in awk
我有一個包含字符串的變量。 現在,我想在awk
使用此變量來放置單詞邊界。 我幾乎可以做到,但是工作dot
符號不起作用。 如何處理。 我必須堅持使用awk
因為我還要根據列采取其他措施。
echo $x
sam
cat foo
t1.sam sample
sam bla
sample sam
awk -v test="$x" '$1~"\\<"test"\\>"' foo
t1.sam sample
sam bla
grep -w
提供所需的結果,但不能使用, grep '\\<sam\\>' foo
也可以。但是同一regex
在awk
不起作用。
添加了示例:如果a != 1
則打印所有行。 如果a=1
則檢查$1
包含sam(帶邊界),如果包含,則打印所有行。
a=1;
x=sam;
if [ $a -eq 1 ];then
awk -v test="$x" '$1 == test' foo #Print all the lines where $1 is sam.
else
awk -v test="$x" '$1 ~ /./' foo #print all the lines where $1 is something.
fi
當a != 1
sam bla
當a == 1
t1.sam sample
sam bla
sample sam
DOT不被視為單詞字符,因此邊界斷言在此之后不起作用.
最好在這里使用相等性:
awk -v test="$x" '$1 == test' file
sam bla
編輯:根據您編輯的問題,您可以使用:
a=1
awk -v a=$a -v test="$x" '(a != 1 && $1 == test) || (a == 1 && $1 ~ test)' file
t1.sam sample
sam bla
sample sam
a=0
awk -v a=$a -v test="$x" '(a != 1 && $1 == test) || (a == 1 && $1 ~ test)' file
sam bla
聽起來您想創建一個可選的過濾器,如下所示:
awk -v test="$test" 'length(test) && $1 == test || !length(test)' file
現在,如果外殼變量$test
為空,則將打印所有行。 否則,只有第一個字段等於$test
才是。
使用文件:
$ test=sam
$ awk -v test="$test" 'length(test) && $1 == test || !length(test)' file
sam bla
$ test=
$ awk -v test="$test" 'length(test) && $1 == test || !length(test)' file
cat foo
t1.sam sample
sam bla
sample sam
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.