Bash and Linux

Replace a config value in place

easysed Must-do

Problem statement

The database is running out of connections and you need to raise max_connections to 500 in app.conf without opening an editor, for example from a deploy script. Change only the active setting; the commented-out line must stay as it is. Edit the file in place.

app.conf

Bash
# api server settings
listen_port=8080
max_connections=100
log_level=info
# max_connections=50 was the old default

Examples

Example 1

Input: Run the command, then `cat app.conf`.

Output: # api server settings listen_port=8080 max_connections=500 log_level=info # max_connections=50 was the old default

Explanation: The ^ anchor stops the comment line from matching.

Hints

Approach

Optimal

s/pattern/replacement/ is sed's substitute command. ^max_connections= only matches when the key is at the very start of a line, which skips the comment. .* swallows the old value, whatever it is, so the command works no matter what the current number is. -i writes the result back to the same file instead of printing it. Single quotes keep the shell from touching .*.

Bash
sed -i 's/^max_connections=.*/max_connections=500/' app.conf

Follow-up questions

  • How would you add the key if it is not present at all?
  • How would you make the change idempotent and report whether the file changed?

Frequently asked questions

BSD sed (macOS) requires a backup suffix argument after -i, so sed -i 's/...//' file treats the script as the suffix. Use sed -i '' 's/.../.../' file on macOS, or sed -i.bak '...' file, which works on both GNU and BSD and keeps a backup.

Use double quotes so the variable expands, e.g. sed -i "s/^max_connections=.*/max_connections=$N/" app.conf. If the value can contain /, pick another delimiter such as s|...|...|, otherwise the value ends the expression early.