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
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
- How do you use awk to sum or average a column? [Advanced]
- What is the difference between sed -i and sed without -i? [Advanced]
- What is the difference between NR and NF in awk? [Advanced]
- How do you split a string on a delimiter in Bash? [Intermediate]
- What is an associative array, and how do you use one? [Intermediate]
- How would you write a health-check script that polls a URL until it returns 200? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]
- What is the difference between glob expansion and regex in the shell? [Intermediate]