我最近在使用grep命令时遇到了一些问题。
我已经找到了只显示grep搜索的最后一行的方法:
grep PATERN FILE_NAME | tail -1
我还找到了在多个选定文件中进行grep搜索的方法:
find . -name "FILE_NAME" | xargs -I name grep PATERN name
现在,我只想获得每个文件的grep结果的最后一行。我试过这个:
find . -name "FILE_NAME" | xargs -I name grep PATERN name | tail -1
这只返回最后一个文件的最后一个值,我希望每个文件都有最后一个匹配的模式。
发布于 2013-02-15 07:04:19
for f in $(find . -name "FILE_NAME"); do grep PATTERN $f | tail -1; done
发布于 2020-02-02 01:25:22
Sort有一个uniq选项,允许您从许多行中只选择一行。试试这个:
grep PATTERN FILENAMES* | tac | sort -u -t: -k1,1
说明: Grep将为文件中的每个匹配项返回一行。这看起来像这样:
$ grep match file*
file1.txt:match
file1.txt:match2
file2.txt:match3
file2.txt:match4
我们想要的是输出中的两行:
$ ???
file1.txt:match2
file2.txt:match4
您可以将其视为一种表,其中第一列是文件名,第二列是匹配,其中的列分隔符是“:”字符。
我们的第一个管道反转输出:
$ grep match file* | tac
file2.txt:match4
file2.txt:match3
file1.txt:match2
file1.txt:match
我们要排序的第二个管道如下:取出第一个唯一行(-u),其中要分组的键是第一个唯一行(-k1,1,从第一列到第一列的键),我们用':‘作为分隔符(-t:)将数据拆分成多个列。它还将对我们的输出进行排序!及其输出:
$ grep match file* | tac sort -u -t: -k1,1
file1.txt:match2
file2.txt:match4
发布于 2013-02-15 06:59:12
您也可以使用find来执行命令:
find . -name "<file-name-to-find>" -exec grep "<pattern-to-match>" "{}" ";" | tail -1
"{}“是文件名,请在编写命令时注意shell全局和扩展
https://stackoverflow.com/questions/14885554
复制相似问题