0

I am trying to assign a variable to the result of a regex substitution in bash. For instance, when I run

echo $initialvar | perl -pe 's/.+(Some_Dir\/)(.+)/\2/'

I get the desired output from the echo. How would I assign a newvar to the resulting output?

I've tried:

newvar= "$($initialvar | perl -pe 's/.+(Some_Dir\/)(.+)/\2/')"
newvar= echo $initialvar | perl -pe 's/.+(Some_Dir\/)(.+)/\2/'

but none of them work

Sos
  • 1,783
  • 2
  • 20
  • 46

2 Answers2

2

You can use either of the following:

newvar=$(echo "$initialvar" | perl -pe 's/.+(Some_Dir\/)(.+)/\2/')
newvar=`echo "$initialvar" | perl -pe 's/.+(Some_Dir\/)(.+)/\2/'`
tripleee
  • 175,061
  • 34
  • 275
  • 318
danrodlor
  • 1,329
  • 8
  • 16
2

As for your question, it seems to consist of two challenges: One being assigning the output of running a command to a BASH variable, and the other being piping the content of a variable to the standard input of a Perl program.

One

foo=$(bar)

runs bar and saves its output to the BASH variable $foo.

The other

Any of

echo "$foo" | bar
bar <(echo "$foo")
bar <<< "$foo"

runs bar with the content of $foo piped to its standard input

Combining the two

baz=$(bar <<< "$foo")

sets $baz to the value produced by bar having the content of $foo sent to its standard input.


Secondly, a few Perl-related suggestions peripherally related to your question:

I might instead use perl -nE:

  • -n will loop through each line like -p, but won't print by default.
  • -E will evaluate like -e, but with experimental features like say enabled.

You can avoid escaping the slash in Some_Dir/ by using another separator, e.g. s!...!...! or m!...!. Instead of replacing with s//, since you're just printing "Some_Dir/" if it matches, you might as well go and do that directly:

perl -nE 'say (m!Some_Dir/! ? "Some_Dir/" : $_)'

So:

newvar=$(perl -nE 'say (m!Some_Dir/! ? "Some_Dir/" : $_)' <<< "$initialvar")
tripleee
  • 175,061
  • 34
  • 275
  • 318
sshine
  • 15,635
  • 1
  • 41
  • 66