开发者

adding or changing variable value

I want to add the following line to /etc/my.cnf

server-id=1789051

T开发者_JAVA技巧he line may or may not be there. If it is there, it is usually server-id=1 If my IP is 192.178.90.51 then the server id should be 1789051

I want to know if a shell script or a command can do it.


This will replace the line in the same position in the file, if it exists, rather than moving it to the end. If it doesn't exist, it will append it to the end of the file.

sed  '1{x;s/^$/server-id=1789051/;x};/^server-id=/{s/^.*$//;x};${G;s/\n//}' /etc/my.cnf


sed --in-place --expression='$aserver-id=1789051' --expression='/^server-id=/d' \
    /etc/my.cnf


one way with awk

#!/bin/bash
ip=1.2.3.4
awk -v ip="$ip" '/server-id/{
    $0="server-id="ip;f=0
    f=1
    g=1
}
{print}
END{
  if(g==0){ print "server-id="ip  }
}' file

output when there is "server-id"

$ more file
1
2
server-id=1
end
$ ./shell.sh
1
2
server-id=1.2.3.4
end

output when there is no "server-id"

$ more file
1
2
end
$ ./shell.sh
1
2
end
server-id=1.2.3.4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜