簡體   English   中英

Shell:在文件中查找關鍵字並獲取以下行的內容

[英]Shell: Find a keyword in a file and get the content of the following lines

我想編寫一個Shell腳本,它可以找到一個特定的單詞並獲取以下各行的內容。

例如我有一個文件:

...[not interested info]...
Keyword: YES
wanted line 1
wanted line 2
wanted line 3
...[not interested info]...

我想搜索關鍵字“是”,並得到以下3行(假設下面的行數是固定的,在這種情況下為3):

wanted line 1
wanted line 2
wanted line 3

我知道如何使用grep獲取關鍵字行,但不知道如何獲取以下行。

怎么樣

grep -A 3 YES

YES之后打印3行尾隨上下文( -A 3 )。

我在考慮以下方面:

while read line
do
  if [ "" != `grep YES $line` ]; then
    echo read line
    echo read line
    echo read line
  fi
done

這很古怪,但是我不知道有什么更優雅的方法。 本質上,這就是逐行讀取文件並檢查每行上的grep輸出,而不是讓grep自己遍歷整個文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM