我有一个包含许多文本文件的目录。我想在文件的特定行中搜索给定的字符串(例如仅在每个文件的第 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/