Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

input variable:

echo $x
sam

input data:

cat foo
t1.sam sample
sam bla
sample sam

What I am getting:

awk -v test="$x" '$1~"\<"test"\>"' foo
t1.sam sample
sam bla

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

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

desired output:

when a != 1

sam bla

when a == 1

t1.sam sample
sam bla
sample sam
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

Using your file:

$ 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...