用sed将一段代码附加到my.cnf

时间:2014-09-03 19:26:20

标签: linux sed

我正在尝试设置一个bash脚本,以便将一些代码行附加到/etc/mysql/my.cnf

[mysqld] <-- new code needs to append here
old code
old code
old code

应该导致

[mysqld]
# set default collation
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
old code
old code
old code

我尝试了以下操作,但它不起作用。

#!/usr/bin/env bash

echo "Set default collation to UTF-8 in /etc/mysql/my.cnf"

sudo sed -i 'a\
# set default collation\
collation-server = utf8_unicode_ci\
init-connect='SET NAMES utf8'\
character-set-server = utf8\
,/[mysqld]/d' /etc/mysql/my.cnf

4 个答案:

答案 0 :(得分:4)

sed '/\[mysqld\]/a # set default collation\
collation-server = utf8_unicode_ci\
init-connect='\''SET NAMES utf8'\''\
character-set-server = utf8\' /etc/mysql/my.cnf

你可以使用append命令(a),但你需要它来操作正确的行,即匹配/\[mysqld\]/的行(这一部分在开头时将sed操作限制为只有匹配的行)。

下一个棘手的部分是'\''。基本上,如果你在单引号内,你就不能逃避单引号。你所能做的就是完成字符串(&#39;)。然后,您处于正常的bash环境中,这样您就可以传递转义的单引号(\&#39;),然后启动下一个单引号字符串(&#39;)。由于它们没有空格分隔,bash会将它们合并在一起并将它们作为单个参数传递给sed(sed命令参数)。

至于bash脚本部分,你可以这样做:

#!/bin/bash

file="/etc/mysql/my.cnf"
if [ -w "$file" ] #Check if you have write permissions
then
  echo "Setting default collation to UTF-8 in /etc/mysql/my.cnf" 
  sed '/\[mysqld\]/a # set default collation\
collation-server = utf8_unicode_ci\
init-connect='\''SET NAMES utf8'\''\
character-set-server = utf8\' -i "$file"

else
  echo "Can't write to $file. ry running the script with 'sudo'."
fi

答案 1 :(得分:1)

您可以使用:

sed 's/\[mysqld\]/[mysqld]\
# set default collation\
collation-server = utf8_unicode_ci\
init-connect='\''SET NAMES utf8'\''\
character-set-server = utf8/' /etc/mysql/my.cnf

答案 2 :(得分:1)

完整的解决方案,在一个地方:

#!/usr/bin/env bash

file="/etc/mysql/my.cnf"
if [ -w "$file" ] #Check if you have write permissions
then
  echo "Setting default collation to UTF-8 in /etc/mysql/my.cnf"
  sed '/\[mysqld\]/a # set default collation\
collation-server = utf8_unicode_ci\
init-connect='\''SET NAMES utf8'\''\
character-set-server = utf8\' -i $file

else
  echo "Can't write to $file. Try running the script with 'sudo'."
fi

答案 3 :(得分:0)

你可以这样做:

awk '/\[mysqld\]/ {$0=$0"\nnew data\nadd here"}1' file

使用您的数据:

awk '/\[mysqld\]/ {$0=$0"\n# set default collation\ncollation-server = utf8_unicode_ci\ninit-connect="q"SET NAMES utf8"q"\ncharacter-set-server = utf8"}1' q="'" file
[mysqld]
# set default collation
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
old code
old code
old code

由于awk代码中的单引号有些复杂,您只需将其添加到变量中,然后在代码中使用它。