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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]