使用 grep|sed|awk 從標準輸入測試正規表示式

使用 grep|sed|awk 從標準輸入測試正規表示式

有時,我想測試我的正規表示式是否正確。

如何regex從標準輸入進行反向比對?

Fe 我可以將字串與提供的正規表示式相匹配,例如:

grep "\(foo\)-bar"
foo
bar
foo-bar
foo-bar #Match found

我想做的是相反的,像這樣:

$ grep "This is one string"
\(This\) #Will send "This" to stdout
This?.*  #Will send full match

這是否可以在沒有太多腳本的情況下實現?

答案1

在 shell 中定義以下函數(您可以直接鍵入它,或將其放入您的 中~/.bashrc):

testregex() {
  [ "$#" -eq 1 ] || return 1
  while IFS= read -r line; do
    printf '%s\n' "$1" | grep -Eoe "$line"
  done
}

然後您可以如下測試正規表示式:

$ testregex 'This is a line'
This            <--input
This            <--output
This?.*         <--input
This is a line  <--output
slkdjflksdj     <--input with no output (no match)
s.*             <--input
s is a line     <--output
$               <--I pressed Ctrl-D to end the test

答案2

您可以使用-“文件”來搜索,它將使用標準輸入作為“乾草堆”來搜索匹配的“針”:

$ grep -oE '[aeiou]+' -
This is a test  < input
i               > output
i               > output
a               > output
e               > output
whaaaat?        < input
aaaa            > output

使用Ctrl-D發送EOF和結束流。

不過,我不相信您可以對-f從文件中讀取模式清單的開關使用標準輸入執行相同的操作。但是,如果您在一個語料庫上有很多文字模式,您可以:

grep -f needle-patterns haystack.txt

其中needle-patterns是每行一個正規表示式的純文字檔。

相關內容