Reputation: 48
I'm sure this is really simple, but I have been having some issues.
I'm trying to create a bash script to update a line in a config file based on a argument passed to it.
The config file looks like this:
//globalConfig.php
'General' => array(
'env_name' => 'Global',
'project_name' => 'ProjectName',
'version' => 'x.x.x'
),
And I am trying to create a script that changes the 'version' value. The script I have ended up with, which doesn't work is this:
#!/usr/bin/env bash
sed -i "s/^\'version\'.*/\'version\' => \'$1\'/" globalConfig.php
Thanks for your help!
Upvotes: 1
Views: 477
Reputation: 437111
Try (using GNU sed
, as implied by your question):
sed -i -r "s/^(\s*'version'\s*=>).*/\1 '$1'/" globalConfig.php
-r
enables support for extended regular expressions, which allows for definition of capture group (\s*'version'\s*=>)
using the expected modern syntax.
\s*
matches any (potentially empty) run of whitespace, making for more flexible matching.\1
in the replacement operand refers to what the first (and only) capture group captured, which makes it unnecessary to repeat the 'version' =>
part.
Note that $1
is expanded by the shell, up front, to supply the replacement value, which assumes that the value of $1
doesn't break the script that sed
sees as a result; specifically, $1
must not contain (unescaped) /
and \
instances.
As for what you tried:
Inside "..."
(a double-quoted shell string), '
chars. can be used as-is - do not \
-escape them.
Since ^
matches the start of the line, 'version'
won't be matched immediately after, because there is intervening whitespace in your sample input.
Upvotes: 1