Bash

按文本塊/行 Grep

  • January 22, 2017

我有文本,其中包含一些行。所以,我需要製作幾行的 GREP。例如,我有重複的文本,我應該 GREP 獲取具有此重複關鍵字的行。

grep -o "test|test2" textfile

我的文字:

123|never for your|test
123421|never for your|test2
123412|never for your|test3
12341|never for your|test4
12311|never for your|test2
123312312|never for your|test
123321312|never for your|test2

我應該:

123|never for your|test
123421|never for your|test2
123312312|never for your|test
123321312|never for your|test2

它可以工作,但不能按我的意願工作。它在文本中搜尋所有單詞“test”和“test2”。但我想獲得文本塊,比如一些模式,只有在“test”之後才會出現“test2”。你有什麼想法嗎?

使用 sed 的簡短 shell 腳本。列出第二種情況的行號,並與第一種情況的行號進行比較。列印匹配對。使用第一個參數作為文件名。可以很容易地擴展為將第二個和第三個參數作為匹配的模式。可以另存為 findnext.sh,然後執行:

$ sh findnext.sh testfile

應該很快,因為它只涉及文件的兩次傳遞,並且具有完全可移植的優點。

#!/bin/sh 
# Line numbers matching test1
mt2=$(sed -ne '/test1/=' < $1 | tr '\n' '/')

for l in $(sed -ne '/test/=' < $1); do
   nextline=$(expr $l + 1)
   [ "${mt2#*$nextline/}" != "$mt2" ] && sed -ne $l,${nextline}p <$1
done

引用自:https://serverfault.com/questions/827764