
時には正規表現が正しいかどうかをテストしたい時があります。
regex
標準入力で逆方向マッチングを実行するには?
Fe I は、文字列を提供された正規表現と一致させることができます。たとえば、次のようになります。
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
シェルで次の関数を定義します(直接入力するか、シェルに入れることができます~/.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
1行に1つの正規表現を含むプレーンテキストファイルがあります。