1

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.

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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: I would have thought that the double-dash long options was a clear enough indicator that this is, indeed, GNU sed.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.