假设我有一个这样的文件集合:
echo -e "apple\n cherry" >> f1.txt;
echo -e "grape\n strawberry" >> f2.txt;
echo -e "orange\n cherry" >> f3.txt; 我要找到每个有"cherry“字样的文件。我可以这样做:
ls *.txt | xargs cat | grep cherry但这只返回f1和f3中匹配的两行,而不显示“源”文件,如下所示:
cherry
cherry我想看看这些匹配的文件-大概是这样的:
f1.txt -> cherry
f3.txt -> cherry有没有一种方法可以简单地从命令行执行此操作?
发布于 2012-03-29 12:19:55
jcomeau@intrepid:/tmp$ echo -e "apple\n cherry" >> f1.txt;
jcomeau@intrepid:/tmp$ echo -e "grape\n strawberry" >> f2.txt;
jcomeau@intrepid:/tmp$ echo -e "orange\n cherry" >> f3.txt;
jcomeau@intrepid:/tmp$ grep cherry *txt
f1.txt: cherry
f3.txt: cherry发布于 2012-03-29 12:21:15
-l选项意味着grep将只打印匹配的文件名,而不打印匹配的行,因此您的任务可以通过以下方式完成:
$ grep -l cherry *.txt
f1.txt
f3.txt(请注意,对于此任务,ls和xargs是不必要的,grep将除第一个位置参数之外的所有参数都视为要查看的文件)
发布于 2012-03-29 12:22:29
尝试使用grep -H打印文件名和匹配项。从手册页:
-H, --with-filename
Print the file name for each match. This is the default when
there is more than one file to search.我发现这在结合使用grep和find时很有用。
https://stackoverflow.com/questions/9918997
复制相似问题