1. 程式人生 > >grep -A -B -C 顯示抓取的前後幾行參數

grep -A -B -C 顯示抓取的前後幾行參數

參數 tween line 字串 抓取 his 站點 顯示 ces

我經常用grep找東西,比如用戶名和密碼。大部分站點和用戶名和密碼都是在一樣的,方便grep查找。有時,為了文本好看,我會放在多行。比如 wikipedia多個語言版本上有多個賬號,就放在wikipedia總欄目下。這時,光 grep wikipedia 密碼文件.txt 就不行了。因為實際的用戶名和密碼在匹配那行的下面呢。

這是 -A 開關就有用了。

grep手冊中的解釋:

Context Line Control

-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.

-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches. With the -o or --only-matching
option, this has no effect and a warning is given.

-C NUM, -NUM, --context=NUM
Print NUM lines of output context. Places a line containing a
group separator (--) between contiguous groups of matches. With
the -o or --only-matching option, this has no effect and a
warning is given.

簡單翻譯就是,-A -B -C 後面都跟阿拉伯數字,-A是顯示匹配後和它後面的n行。-B是顯示匹配行和它前面的n行。-C是匹配行和它前後各n行。總體來說,-C覆蓋面最大。用它保險些。哈哈。這3個開關都是關於匹配行的上下文的(context)。

於是,

  grep -A 4 wikipedia 密碼文件.txt 

就是搜索密碼文件,找到匹配“wikipedia”字串的行,顯示該行後後面緊跟的4行。

這種方法比用程序打開該文件搜索關鍵字要快得多!

轉自:http://pengyou.rijiben.org/node/2952

grep -A -B -C 顯示抓取的前後幾行參數