2

I want to programmatically replace little placeholder with static content like the user name or working path.

Is there a possibility in bash that I can dynamically execute my perl replacement state like:

GROUPNAME="$(id -g -n $USER)"
perl -pi -e 's/\(PLACEHOLDER\)/' + "$GROUPNAME" + '/g' filepath/file

it would be the enormously good if I could also adapt this dynamical behaviour for the placeholder. But first things first. How do I concatenate these strings?

learningbee
  • 333
  • 1
  • 5
  • 11
BeJay
  • 425
  • 4
  • 15

2 Answers2

6

Remove " + " (spaces and plus). Bash does automatic concatenation for adjacent strings.

echo 'hi!'t"here"  # hi!there

Generating Perl code in this way is only safe because the output of id -g -n $USER won't contain \, $, @ or /.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
2

You were going for

GROUPNAME="$(id -g -n $USER)"
perl -i -pe's/\(PLACEHOLDER\)/'"$GROUPNAME"'/g' filepath/file

But there's no reason to generate Perl code. That is very error prone. Instead, use one of the following:

export GROUPNAME="$(id -g -n $USER)"
perl -i -pe's/\(PLACEHOLDER\)/$ENV{GROUPNAME}/g' filepath/file

or

GROUPNAME="$(id -g -n $USER)" perl -i -pe's/\(PLACEHOLDER\)/$ENV{GROUPNAME}/g' filepath/file
ikegami
  • 367,544
  • 15
  • 269
  • 518