[英]How to match lines where a variable is found somewhere between two characters with grep?
我需要从文件中的所有行输出BASH变量$a
,它们也位于同一行的字母“ A”和“ Z”之间。
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.
如果$a
设置为“ cat”,则仅输出以下行,因为在这些行的两个字符之间找到了“ cat”:
A the cat went to the river Z
The A cat then Z swam to the lake.
如果将$a
设置为“ then”,则仅输出此行,因为在两个字符之间找到了“ then”:
The A cat then Z swam to the lake.
我已经尝试了这些,但是没有一个起作用:
grep "A*[$a]+*Z" file.txt
grep "A(.*)[$a]+(.)Z" file.txt
grep "[A]+*[$a]+*[Z]+" file.txt
如何使用grep
或类似的BASH工具在两个字符之间的某个位置找到变量的行匹配?
这应该工作:
grep "A.*$a.*Z" file.txt
假定$a
不包含任何在正则表达式中具有特殊含义的字符。
您所有的尝试都使用[$a]
,这是完全错误的。 [chars]
与单个字符匹配是这样的中的任何一个chars
的括号内。
尝试以下命令:
egrep "\b(A)\b.*[\$a].*\b(Z)\b" * --color
这在以下文本中不起作用:
A the cat went $a to the river Z and A goes to $a for Z reason.
此正则表达式给您A the cat went $a to the river Z and A goes to $a for Z
作为输出。
awk
解决方案
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.
您应该可以只使用grep或egrep。
grep "$a" filename.txt
或者,如果我理解正确,那么您要确保每边至少有一个字符,那会更好
egrep ".+$a.+" filename.txt
要么
grep -P ".+$a.+" filename.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.