linux - 使用 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
吗?
解决方案
改用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
推荐阅读
- reactjs - 如何在reactjs中从redux状态中过滤掉项目
- reactjs - 使用带有反应的输入类型范围缩放图像
- linux - Bash 中的输出格式
- reactjs - 如何使用 React/TypeScript 中的钩子进行部分状态更新
- python - TypeError:Update_Profile() 缺少 1 个必需的位置参数:'self'
- java - 自动生成 CHANGELOG.md 文件
- trace32 - Trace32 - PBI=MCIServer 非法逗号错误
- c - 实现一个名为翻转的函数;它将一个数字作为输入并翻转它的最后 N 个数字
- c++ - Sqlite3 C++ 数据库被锁定
- java - 如何将 MySQL 数据库注入项目文件夹