I have this input.txt
file:
Dog walks in the park
Man runs in the park
Man walks in the park
Dog runs in the park
Dog stays still
They run in the park
Woman runs in the park
I want to search for matches of the runs?
regular expression and output them to a file, while highlighting matches with two asterisks on both sides of the match. So my desired output is this:
Man **runs** in the park
Dog **runs** in the park
They **run** in the park
Woman **runs** in the park
What I want to do is to write a function that would be a wrapper for this perl one-liner (and it would do few other things) and then invoke it with a regular expression as its parameter. I wrote following script:
#!/bin/bash
function reg {
perl -ne 's/($1)/**\1**/&&print' input.txt > regfunctionoutput.txt
}
function rega {
regex="$1"
perl -ne 's/($regex)/**\1**/&&print' input.txt > regafunctionoutput.txt
}
perl -ne 's/(runs?)/**\1**/&&print' input.txt > regularoutput.txt
reg 'runs?'
rega 'runs?'
Output of first perl one-liner is what I want. But when I try to wrap it in a reg
function and pass the expression as a parameter, instead of desired output I get:
****Dog walks in the park
****Man runs in the park
****Man walks in the park
****Dog runs in the park
****Dog stays still
****They run in the park
****Woman runs in the park
I thought the issue was some conflict between $1
as a function parameter and the first capturing group in the perl one-liner. So I created a second function rega
which first assigns that expression to a different variable and only then passes it to perl. But the output is the same as previous function.
So, how can I pass a regular expression to a perl one-liner inside the function? What I am doing wrong?