What would be the right syntax to perform an inplace update to a file from:
"redis"=>array(
'enabled' => false,
to
"redis"=>array(
'enabled' => true,
I’ve tried things like but it’s not working
sed -i "s/"redis"=>array(n 'enabled' => false/"redis"=>array(n 'enabled' => true/" input.php
4
Answers
You can use
See the online demo:
Output:
Here,
/"redis"=>array($/
– match a line that ends with"redis"=>array(
string and{N;s/('"'"'enabled'"'"' => )false/1true/}
–N
appends a newline char and adds the next line to the pattern space, ands/('enabled' => )false/1true/
matches and captures into Group 1'enabled' =>
substring and then just matchesfalse
and the1true
replaces the match with the Group 1 value +true
substring.If you have
gnu sed
then your attempted approach will fine with-z
option:Explanation:
-z
: separate lines by NUL character-E
: Enable extended regex mode("redis"=>array(n[[:blank:]]*'enabled' => )false
: Match"redis"=>array(
line followed by line break and'enabled' =>
part in capture group #1, followed byfalse
.1true
: puts captured value from group #1 followed bytrue
With
perl
:search.txt
file containing content to be searchedreplace.txt
file containing content to be used for replacementip.txt
file on which the substitution has to be performed-0777
slurp entire file contents as a single string, so this solution isn’t suitable if input file is too large to fit memory requirements$#ARGV
is used to know which file is being read$s
saves the search text,$r
saves the replacement texts/Q$s/$r/gr
here,Q
is used to match search text literallyperl -i -0777 ...
for in-place modification.See my blog post for more examples and alternatives.
This might work for you (GNU sed):
Look for a line that ends
"redis"=>array(
, print it and fetch the next line.If that line contains
'enabled' => false,
replacefalse
bytrue
.