提取正则表达式匹配 grep 的第一个位置

Extract first position of a regex match grep

大家早上好,

我有一个包含多行的文本文件。我想在其中找到一个规则的图案并使用 grep 打印它的位置。

例如:

ARTGHFRHOPLIT
GFRTLOPLATHLG
TGHLKTGVARTHG

我想在文件中找到L[any_letter]T并打印L的位置和三字母代码。在这种情况下,结果将是:

11 LIT
8 LAT
4 LKT

我用 grep 写了一段代码,但它 return 不是我需要的。代码是:

grep -E -boe "L.T" file.txt

它returns:

11:LIT
21:LAT
30:LKT

如有任何帮助,我们将不胜感激!!

Awk 更适合这个套件:

awk 'match([=10=], /L[[:alpha:]]T/) {
print RSTART, substr([=10=], RSTART, RLENGTH)}' file

11 LIT
8 LAT
4 LKT

这是假设每行只有一个这样的匹配项。


如果每行可以有多个 重叠 匹配,则使用:

awk '{
   n = 0
   while (match([=11=], /L[[:alpha:]]T/)) {
      n += RSTART
      print n, substr([=11=], RSTART, RLENGTH)
      [=11=] = substr([=11=], RSTART + 1)
   }
}' file

使用您显示的示例,请尝试以下 awk 代码。在 GNU awk 中编写和测试,应该在任何 awk.

中工作
awk '
{
  ind=prev=""
  while(ind=index([=10=],"L")){
    if(substr([=10=],ind+2,1)=="T" && substr([=10=],ind+1,1) ~ /[a-zA-Z]/){
      if(prev==""){ print prev+ind,substr([=10=],ind,3)   }
      if(prev>1)  { print prev+ind+2,substr([=10=],ind,3) }
    }
    [=10=]=substr([=10=],ind+3)
  prev+=ind
  }
}'  Input_file

说明:为以上代码添加详细说明。

awk '                                                     ##Starting awk program from here.
{
  ind=prev=""                                             ##Nullifying ind and prev variables here.
  while(ind=index([=11=],"L")){                               ##Run while loop to check if index for L letter is found(whose index will be stored into ind variable).
    if(substr([=11=],ind+2,1)=="T" && substr([=11=],ind+1,1) ~ /[a-zA-Z]/){      ##Checking condition if letter after 1 position of L is T AND letter next to L is a letter.
      if(prev==""){ print prev+ind,substr([=11=],ind,3)   }   ##Checking if prev variable is NULL then printing prev+ind along with 3 letters from index of L eg:(LIT).
      if(prev>1)  { print prev+ind+2,substr([=11=],ind,3) }   ##If prev is greater than 1 then printing prev+ind+2 and along with 3 letters from index of L eg:(LIT).
    }
    [=11=]=substr([=11=],ind+3)                                   ##Setting value of rest of line value to 2 letters after matched L position.
  prev+=ind                                               ##adding ind to prev value.
  }
}'  Input_file                                            ##Mentioning Input_file name here.

查看 @anubhava you might also sum the RSTART + RLENGTH and use that as the start for the substr 的答案以获取每行和每个单词的多个匹配项。

while 循环获取当前行,并在每次迭代中更新其值,方法是将其设置为紧跟在最后一次匹配之后的部分,直到字符串末尾。

请注意,如果您在正则表达式中使用 .,它可以匹配任何字符。

awk '{
  pos = 0
  while (match([=10=], /L[a-zA-Z]T/)) {
    pos += RSTART;
    print pos, substr([=10=], RSTART, RLENGTH)
    [=10=] = substr([=10=], RSTART + RLENGTH)
   }
}' file

如果文件包含

ARTGHFRHOPLIT
GFRTLOPLATHLG
TGHLKTGVARTHG
ARTGHFRHOPLITLOT LATTELET
LUT

输出为

11 LIT
8 LAT
4 LKT
11 LIT
12 LOT
14 LAT
17 LET
1 LUT