Testing regex from stdin using grep|sed|awk

awkcommand linegrepregular expressionsed

Sometimes, I want to test is my regex correct.

How can I do reverse regex match from stdin?

F.e. I can match a string with provided regex, like:

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

What I would like to do, is the opposite, something like this:

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

Is this somehow possible without much scripting?

Best Answer

You can use - as the "file" to search, which will use standard input as the "haystack" to search for matching "needles" in:

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

Use Ctrl-D to send EOF and end the stream.

I don't believe, though, that you can do the same to use standard input for the -f switch which reads a list of patterns from a file. However, if you have a lot of patterns to text on one corpus, you can:

grep -f needle-patterns haystack.txt

where needle-patterns is a plaintext file with one regular expression per line.

Related Question