wackattack has asked for the wisdom of the Perl Monks concerning the following question:

Any way I can perform Perl 1 liners in a bash script and then feed the results back into a bash variable? I need to do some regular expressions on some strings.

For instance:
INPUT="A String of text" RESULTS= perl -e s/bad_text/good_text/g
and then continue to do operations on $RESULTS within the bash script. I'm modifying a previously written bash script and regular expressions are so easy in perl.

Replies are listed 'Best First'.
Re: Embedding perl in bash
by AppleFritter (Vicar) on Oct 22, 2015 at 20:44 UTC

    Yes, this can easily be done using backticks:

    #!/bin/sh INPUT="A String of text"; RESULTS=`echo $INPUT | perl -pe 's/String/Wall/g'` echo $RESULTS # A Wall of text
Re: Embedding perl in bash
by NetWallah (Canon) on Oct 22, 2015 at 21:40 UTC
    Backtics are considered 'old school'. Here is an option using perl %ENV:
    export INP2="A String of Text" RES=$(perl -e '($x=$ENV{INP2})=~s/String/Wall/;print $x') echo $RES A Wall of Text

            The best defense against logic is ignorance.

      Is the use of the outer parens creating a form an inline shell function here?
Re: Embedding perl in bash
by MidLifeXis (Monsignor) on Oct 22, 2015 at 20:43 UTC

    I know that this is a Perl site, but is sed not up to the task?

    --MidLifeXis

Re: Embedding perl in bash
by Laurent_R (Canon) on Oct 22, 2015 at 21:43 UTC
    Yes, backticks is certainly the most flexible way.
    INPUT1="FOO1" INPUT2="FOO2"; RESULT=`perl -E 'for ( @ARGV) { s/FOO/BAR/; say ;}' $INPUT1 $INPUT2`
    Output:
    $ echo $RESULT BAR1 BAR2
Re: Embedding perl in bash
by Corion (Patriarch) on Oct 23, 2015 at 06:09 UTC

    Note that bash itself can also do substitution:

    INPUT="A String of text" RESULTS=${INPUT/bad_text/good_text}
Re: Embedding perl in bash
by stevieb (Canon) on Oct 22, 2015 at 20:38 UTC

    I have never done much shell scripting, but I took a crack at it. Here's one way that seems to work:

    #!/bin/bash INPUT="A string" func() { echo $INPUT | perl -e '$in=<STDIN>; $in=~s/string/thing/g; print $ +in' } RESULTS=$(func) echo $RESULTS

    Output:

    A thing