Passing regular expression as parameter to perl one-liner in bash script

I have 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 to 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 wrapper for this perl one-liner (and it would do few other things) and then invoke it with regular expression as its parameter. I wrote following script:


function reg {
    perl -ne 's/($1)/****/&&print' input.txt > regfunctionoutput.txt

function rega {
    perl -ne 's/($regex)/****/&&print' input.txt > regafunctionoutput.txt

perl -ne 's/(runs?)/****/&&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 reg function and pass expression as 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 though that issue was some conflict between $1 as function parameter and first capturing group in perl one-liner. So I created second function rega which first assigns that expression to different variable and only then passes it to perl. But output is the same as previous function.

So, how can I pass regular expression to perl one-liner inside the function? What I am doing wrong?

Source: bash

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.