[英]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.
不同版本的grep的--null
略有不同,但是通常以某種形式存在。 閱讀您的手冊以獲取詳細信息。
更新:我相信grep的空文件列表是一種合理的解決方案,它將涵蓋絕大多數實際使用案例,但是要完全可移植,如果您的grep
版本不支持任何空輸出,則不是與xargs
一起使用完全安全,因此您必須求助於find
。
find . -maxdepth 1 -type f -exec grep -q "$yourstring" {} \; -exec sed -n '4p;q' {} +
因為find
參數幾乎可以全部用作謂詞,所以-exec grep -q…
部分將最終饋送給sed
的文件過濾為僅包含所需字符串的文件。
嘗試下面的GNU find命令,
find . -maxdepth 1 -type f -exec grep -l 'yourstring' {} \; | xargs -I {} awk 'NR==4{print; exit}' {}
它查找當前目錄中包含特定字符串的所有文件,並打印每個文件中出現的行號4。
這個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.