轉載自:http://www.wenzizone.com/2012/01/06/grep_lines_before_and_after_matched_line.html
grep是一個在文件中查找匹配字符串很有幫助的命令。指到現在,我才知道如何使用grep查看匹配字串的上下行內容。
讓我們看一個例子
ALICE was beginning to get very tired of sitting by her sister on the bank and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?' |
如果我們現在要搜索帶"bank”的行,我們應該這樣寫
# grep bank test.txt
然後我們會得到
her sister on the bank
如果我們現在想要得到這行,和這行前面的一行,我們應該這樣寫
# grep -B1 bank test.txt
得到的結果是這樣的
very tired of sitting by her sister on the bank
如果我們要得到包含"bank”的行和其後面的兩行,我們應該這樣寫
# grep -A2 bank test.txt
這樣得到的結果是這樣的
her sister on the bank and of having nothing to do: once or twice she had peeped
是不是很方便,當然這兩個參數還可以同時使用。至於例子,這裏就不寫了,留着讀者自己去探索吧。
原文可以參考:http://www.jansipke.nl/grep-lines-before-and-after-matched-line
© 2012, 深夜的蚊子. 版權所有. 如轉載,請註明:轉載自 蚊子空間站[http://www.wenzizone.com]