Answer the question
In order to leave comments, you need to log in
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
Result:
sed -i '/cluster/ s|$|\n "version" => '\''1.0'\''|' file
In gray, you just need to escape the quotes, look at the special characters in May and the slash will save you
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"
------- 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,
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question