tags:

views:

31

answers:

3

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

server-id=1789051

The 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.

+1  A: 
sed --in-place --expression='$aserver-id=1789051' --expression='/^server-id=/d' \
    /etc/my.cnf
Teddy
The '--in-place' works with GNU sed - not with POSIX standard versions of sed. The notation used with '$a' (to append at the end) is also unique to GNU sed; the standard versions require a backslash and a newline in the script. That said, it seems to work with GNU sed.
Jonathan Leffler
@Jonathan Leffler: I would have thought that the double-dash long options was a clear enough indicator that this is, indeed, GNU sed.
Teddy
A: 

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
ghostdog74
+1  A: 

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
Dennis Williamson