单词边界以处理awk中的点符号

单词边界以处理awk中的点符号

本文介绍了单词边界以处理awk中的点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串的变量.现在,我想在awk中使用此变量来放置单词边界.我几乎可以做到,但是工作边界不适用于dot符号.如何处理.我必须坚持awk,因为我还要根据列采取其他措施.

I have a variable which contains a string. Now I want to use this variable in awk to put word boundaries. I am nearly able to do, but work boundaries are not working for dot sign. How to deal with this. I have to stick with awk as I have some further actions to take based on columns.

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中不起作用.

grep -w give the desired result but cannot use, also grep '\<sam\>' foo works .but same regex is not working in awk.

添加的示例:如果a != 1,则打印所有行.如果a=1,则检查$1是否包含sam(带边界),如果确实包含,则打印所有行.

Added example: if a != 1 then print all the lines. if a=1 then check if $1 contains sam (with boundaries), if it does then print all the lines.

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

推荐答案

听起来您想创建一个可选的过滤器,如下所示:

It sounds like you want to create an optional filter, something like this:

awk -v test="$test" 'length(test) && $1 == test || !length(test)' file

现在,如果外壳变量$test为空,则将打印所有行.否则,只有第一个字段等于$test的行是

Now if the shell variable $test is empty, all lines are printed. Otherwise, only lines whose first field are equal to $test are.

使用文件:

$ 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

这篇关于单词边界以处理awk中的点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 07:20