Interview Scripting (Bash, Groovy)

How do you use sed to find and replace text in a file (with a backup)? [Advanced]

Answer

I use sed 's/old/new/g' for substitution and sed -i.bak for in-place editing with a backup. The backup makes rollback easy if the replacement is wrong.

Technical explanation

sed without -i writes modified output to stdout and does not change the original file.

sed -i changes the file in place; syntax differs slightly between GNU sed and BSD/macOS sed.

For production edits, test without -i first or write to a temp file and move it into place after validation.

Hands-on example

# Preview first:

sed 's/log_level=debug/log_level=info/g' app.conf

# Edit in place and keep app.conf.bak:

sed -i.bak 's/log_level=debug/log_level=info/g' app.conf

diff -u app.conf.bak app.conf

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions