简体   繁体   中英

How can I pipe a bash variable into a GREP regex in the following command?

I have a command that runs fine as follows:

grep ",162$" xyz.txt | grep -v "^162,162$"

It is basically looking for lines that have a pattern like "number,162" except those where the number is 162.

Now, I want to run many such commands where 162 is replaced with other numbers like

grep ",$159" xyz.txt | grep -v "^159,159$"
grep ",$111" xyz.txt | grep -v "^111,111$"

.. and so on where the same number appears in every part of the command everywhere. So, I need a single place to change the value and the rest of the command can take that value wherever needed.

I tried doing something like this to repeat the number of changes I need to do when I want to try another number

x=162 | grep ",\$x$" xyz.txt | grep -v "^\$x,\$x$"

but it doesn't work. What changes should I do so that everytime I have to change the number value, I just go to the first position of the command and change only the value of x?

Whenever you are piping grep to grep, consider using awk:

var=YOUR_NUM
awk -F, -v pat="$var" '$NF==pat && $1!=pat' file

This plays a little with awk 's fields: by setting the field separator to the comma, you are then able to treat each part separately.
You want to match those cases in which the last field is the given value and the first one is not. This is possible using $NF for the last field and using $1 for the first one.
Also, you can add an extra layer of control by checking NF (number of fields) and making the condition be something like !($1==pat && NF==2) && $NF==pat so that a line like 162,162,162 would be printed. But this really depends on what you want to do.

For example:

$ cat file
hello
hello,162
162,162
$ val=162
$ awk -F, -v pat="$val" '$NF==pat && $1!=pat' file
hello,162

Then it is just a matter of changing $var with the value you want.

If I understand it correctcly, you want something like that:

x=162
grep ",$x\$" xyz.txt | grep -v "^$x,$x\$"

如果您打算单线报价,那就是您的朋友:

X=123 /bin/sh -c 'grep ","$X"$" xyz.txt | grep -v "^"$X","$X"$"'

Single grep command can be used with negative lookbehind:

$ cat xyz.txt 
12,12
112,12
1,12
42,12

$ grep -P '(?<!^12),12$' xyz.txt
112,12
1,12
42,12

Passing variable is tricky

$ x=12
$ grep -P "(?<!"^$x"),"$x"$" xyz.txt
112,12
1,12
42,12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM