Testing regex from stdin using grep|sed|awk
Define the following function in your shell (you can just type it in, or put it in your ~/.bashrc
):
testregex() {
[ "$#" -eq 1 ] || return 1
while IFS= read -r line; do
printf '%s\n' "$1" | grep -Eoe "$line"
done
}
Then you can test a regex as follows:
$ 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
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.