linux - 使用 GREP 搜索特定行的文件

标签 linux bash terminal grep command-line-interface

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

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

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

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

例如
1.txt

file 1
one
two

2.txt

file 2
two
three

我想使用 grep 在每个文件的第 2 行中搜索“two”,然后使用 match 打印文件的第一行。在此示例中,它将是 2.txt,输出应为“文件 2”

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

最佳答案

改用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 ...

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

parse2.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

关于linux - 使用 GREP 搜索特定行的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63488631/

相关文章:

php - 在 Linux 环境中从 PHP 脚本运行应用程序时出现问题

python - 由 python subprocess.Popen(shell=True) 创建的进程的 pid 不是生成的 shell 的 pid

linux - bash 内置命令 "select"无法通过 shell 脚本中的管道工作

python - Scrapy shell 在终端中不断返回无效语法

R: install.package() 没有在 CentOS 6.5 上调用编译器

c - 如何使用 fnmatch

bash - 在 bash shell 中打印星号 ("*")

linux - 如何在 bash 的同一行添加来自不同来源的内容

linux - 按权限过滤文件的命令

macos - 管道和正则表达式 bash 输出