首页 > 解决方案 > 使用 GREP 搜索文件的特定行

问题描述

我有一个包含许多文本文件的目录。我想在文件的特定行中搜索给定的字符串(比如在每个文件的第 2 行和第 3 行中搜索“abc”)。然后,当我找到 A 匹配项时,我想打印匹配文件的第 1 行。

我的方法 - 我正在使用 -n 选项进行 grep 搜索,并将输出存储在不同的文件中,然后在该文件中搜索行号。然后我试图获取文件名,然后打印出它的第一行。

使用我上面提到的方法,我无法获得正确文件的文件名,即使我知道这种方法非常冗长。

有没有更好更快的解决方案?

例如。
1.txt

file 1
one
two

2.txt

file 2
two
three

我想在每个文件的第 2 行中搜索“两个”,grep然后使用 match 打印文件的第一行。在这个例子中,这将是 2.txt,输出应该是“文件 2”

我知道使用sed/更容易,awk但是有什么方法可以使用grep吗?

标签: linuxbashterminalgrepcommand-line-interface

解决方案


改用sed(GNU sed):

解析.sed

1h                 # Save the first line to hold space
2,3 {              # On lines 2 and 3
  /my pattern/ {   # Match `my pattern`
    x              # If there is a match bring back the first line
    p              # and print it
    :a; n; ba      # Loop to the end of the file
  }
}

像这样运行它:

sed -snf parse.sed file1 file2 ...

或作为单行:

sed -sn '1h; 2,3 { /my pattern/ { x; p; :a; n; ba; } }' file1 file2 ...

您可能还想发出文件名,例如使用您的示例数据:

解析2.sed

1h                 # Save the first line to hold space
2,3 {              # On lines 2 and 3
  /two/ {   # Match `my pattern`
    F              # Output the filename of the file currently being processed
    x              # If there is a match bring back the first line
    p              # and print it
    :a; n; ba      # Loop to the end of the file
  }
}

像这样运行它:

sed -snf parse2.sed file1 file2 | paste -d: - -

输出:

file1:file 1
file2:file 2

推荐阅读