簡體   English   中英

如何使用grep匹配在兩個字符之間的某個位置找到變量的行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM