简体   繁体   English

从UNIX Shell,如何查找包含特定字符串的所有文件,然后打印每个文件的第四行?

[英]From UNIX shell, how to find all files containing a specific string, then print the 4th line of each file?

我想查找当前目录中包含给定字符串的所有文件,然后仅打印每个文件的第四行。

grep --null -l "$yourstring" * | # List all the files containing your string
  xargs -0 sed -n '4p;q' # Print the fourth line of said files.

Different editions of grep have slightly different incantations of --null , but it's usually there in some form. 不同版本的grep的--null略有不同,但是通常以某种形式存在。 Read your manpage for details. 阅读您的手册以获取详细信息。

Update: I believe one of the null file list incantations of grep is a reasonable solution that will cover the vast majority of real-world use cases, but to be entirely portable, if your version of grep does not support any null output it is not perfectly safe to use it with xargs , so you must resort to find . 更新:我相信grep的空文件列表是一种合理的解决方案,它将涵盖绝大多数实际使用案例,但是要完全可移植,如果您的grep版本不支持任何空输出,则不是与xargs一起使用完全安全,因此您必须求助于find

find . -maxdepth 1 -type f -exec grep -q "$yourstring" {} \; -exec sed -n '4p;q' {} +

Because find arguments can almost all be used as predicates, the -exec grep -q… part filters the files that are eventually fed to sed down to only those that contain the required string. 因为find参数几乎可以全部用作谓词,所以-exec grep -q…部分将最终馈送给sed的文件过滤为仅包含所需字符串的文件。

Give a try to the below GNU find command, 尝试下面的GNU find命令,

find . -maxdepth 1 -type f -exec grep -l 'yourstring' {} \; | xargs -I {} awk 'NR==4{print; exit}' {}

It finds all the files in the current directory which contains specific string, and prints the line number 4 present in each file. 它查找当前目录中包含特定字符串的所有文件,并打印每个文件中出现的行号4。

This for loop should work: 这个for循环应该工作:

while read -d '' -r file; do
    echo -n "$file: "
    sed '4q;d' "$file"
done < <(grep --null -l "some-text" *.txt)

来自其他用户:

grep -Frl string . | xargs -n 1 sed -n 4p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM