按文字區塊\行進行 Grep

按文字區塊\行進行 Grep

我有文本,其中包含一些行。所以,我需要對幾行進行 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”。你有什麼想法嗎?

答案1

使用 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

答案2

您可以嘗試 grep -E 或egrep。請嘗試這樣

#this will show lines that have test or test2
    grep -E "test|test2" file

如果你想像這樣 test|test2 顯示包含 test 和 test2 的行,請執行下列操作

# This will show lines that has test|test2
    grep "test\|test2" file

答案3

awk可能是您的工具:

awk '/test$/, /test2$/' < block-text-lines.txt 

一般形式是:

awk '/start-pattern/, /end-pattern/{command}'

但由於命令區塊預設為列印,因此只需開始和結束模式就可以了。

退房man awkGnu Awk 使用者指南為了方式更多詳情。

答案4

grep -A 1 "test$" in.txt | grep -B 1 "test2$"

在 grep 手冊中

-A NUM在匹配行之後列印 NUM 行尾隨上下文。

-B NUM在匹配行之前列印 NUM 行前導上下文。

該命令grep -Pzo ".*test$\n.*test2$" in.txt也有效,但在手冊中是「這是高度實驗性的,grep -P 可能會警告未實現的功能」。

相關內容