简体   繁体   中英

How to match lines where a variable is found somewhere between two characters with grep?

I need to output all lines from a file where a BASH variable, $a is found somewhere between the letters "A" and "Z", also on the same line.

A the cat went to the river Z
The A cat then Z swam to the lake.
Then the cat A ate Z some fish.

If $a were set to "cat", then only these lines would be output, because "cat" is found between the two characters on those lines:

A the cat went to the river Z
The A cat then Z swam to the lake.

If $a were set to "then", then only this line would be output, because "then" is found between the two characters:

The A cat then Z swam to the lake.

I have tried these, but none have worked:

grep "A*[$a]+*Z" file.txt

grep "A(.*)[$a]+(.)Z" file.txt

grep "[A]+*[$a]+*[Z]+" file.txt

How can I match lines where a variable is found somewhere between two characters with grep or a similar BASH tool?

This should work:

grep "A.*$a.*Z" file.txt

This assumes that $a doesn't contain any characters that have special meaning in regular expressions.

All your attempts use [$a] , which is totally wrong. [chars] matches a single character that's any one of the chars inside the brackets.

Try Following command :

egrep  "\b(A)\b.*[\$a].*\b(Z)\b" * --color 

This will not work in below text :

A the cat went $a to the river Z and A goes to $a for Z reason.

This regex gives you A the cat went $a to the river Z and A goes to $a for Z as output.

An awk solution

awk '$0~"A.*"x".*"Z' x=$a file
A the cat went to the river Z
The A cat then Z swam to the lake.

You should be able to just use grep or egrep.

grep "$a" filename.txt

or if I am understanding properly then you want to make sure that there is at least one character on each side then this would be better

egrep ".+$a.+" filename.txt

or

grep -P ".+$a.+" filename.txt

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