
我正在嘗試在文件中搜尋模式,如果找到,我想查看該行和另外 10 行結果。
到目前為止我有
grep -n pattern file | cut -d: f1
現在不知道如何使用這個輸出來列印,邏輯如下
sed -n result,(result+10)p file
如果它的模式是多行的,可能會發布一些。
任何幫助表示讚賞
答案1
如果grep -A
不起作用,請嘗試
awk '/pattern/ {for(i=0;i<number_of_lines;i++){print;getline}}' <filename>
否則 sed 有另一個骯髒的解決方案
sed -n '/pattern/ {p;n;p;n;p;...}' <filename>
這裡 p-> print,n -> 到達下一行。所以 p 的數量是要列印的行數
更新:
要用作函數,請編寫 test.sh
jobcheck(){
awk "/$1/"' {for(i=0;i<10;i++){print;getline}}' $2
}
然後就
source test.sh
跑步,
jobcheck "pattern" "file"
更新:根據 Jonathan Leffler 的建議,如果接下來 10 行中的任何一行包含該模式,則應從該行開始計數,以便
pattern ->start printing from here to next 10 lines
blah
blah
pattern ->forget about the last 2 lines, start counting from here
blah
blah
所以更新後的 awk 指令會是這樣的
awk '/pattern/{max_line=NR+2} {if(NR<=max_line) print}' <filename>
同樣裡面的jobcheck也會被改變。乾杯:)
答案2
使用 grep 2.10:
grep -A 10 "pattern" your_file
比賽結束後將列印 10 行
來自grep 手冊頁:
- 數字
--after-context=num
在匹配行之後列印尾隨上下文的 num 行。
使用 GNU awk 3.1.8:
awk '{if(a-->0) {print; next}} /pattern/{print; a=10}' your_file
答案3
我會用:
sed -n '/pattern/{N;N;N;N;N;N;N;N;N;N;p;}'
或者
sed '1,/pattern/{/pattern/!d;}' | sed '12,$d'