简体   繁体   中英

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. 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 .

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.

Give a try to the below GNU find command,

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.

This for loop should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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