簡體   English   中英

單詞邊界以處理awk中的點符號

[英]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也可以。但是同一regexawk不起作用。

添加了示例:如果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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM