D
D
Dmitry Erokhin2015-02-20 11:40:44
bash
Dmitry Erokhin, 2015-02-20 11:40:44

How to replace a string with a new one via bash?

There is a file
There is a text in it:
"server" => [
{
"port" => "2200",
"ntf_port" => "22000",
"ip" => "10.10.10.10",
'role' => 'Client' ,
'cluster' => 'Cluster',
'ntf_sync' => true,
}

After the line 'cluster' => 'Cluster', insert "version" => '1.0' preferably on a new line.
The main problem is that sed which tried to do this does not want to accept this bunch of quotes in the text of the file.
Any suggestions how to do it?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Dmitry Erokhin, 2015-02-20
@erohin_d

Result:
sed -i '/cluster/ s|$|\n "version" => '\''1.0'\''|' file

P
Puma Thailand, 2015-02-20
@opium

In gray, you just need to escape the quotes, look at the special characters in May and the slash will save you

Z
Zaur Abdulgalimov, 2015-02-20
@abdulgalimov

file=`cat file`
echo "------- file -------"
echo "$file"

template="'cluster' => 'Cluster',"
replaceTo="$template\\
'version' => '1.0'"

result=`echo "$file" | sed 's/'"$template"'/'"$replaceTo"'/g'`

echo "------- result -------"
echo "$result"

Execution result:
------- file -------
"server" => [
{
"port" => "2200",
"ntf_port" => "22000",
"ip" => "10.10.10.10",
'role' => 'Client',
'cluster' => 'Cluster',
'ntf_sync' => true,
}
------- result -------
"server" => [
{
"port" => "2200",
"ntf_port" => "22000",
"ip" => "10.10.10.10",
'role' => 'Client',
'cluster' => 'Cluster',
'version' => '1.0',
'ntf_sync' => true,
}

S
Sergey Petrikov, 2015-02-20
@RicoX

Here in one line:
sed '/Cluster/a \"version" => '\''1.0'\''\'

S
ShamblerR, 2015-02-20
@ShamblerR

sed -i 's/^\x27cluster/x27 \x3D\x3E/^\x27Cluster/x27 \x3D\x3E/g' index.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question