Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

How do you use variables inside a `sed` expression safely?

AdvancedConceptText processing: grep, sed, awk, cut, sort, uniq
Answer

Use double quotes so the variable expands, a delimiter that cannot appear in the value, and escape special characters in the replacement (&, \, the delimiter).

new_image="registry.example.com/api:1.4.2"
sed -i "s|^\(\s*image:\).*|\1 ${new_image}|" deploy.yaml

escape_sed_repl() { printf '%s' "$1" | sed 's/[&|\\]/\\&/g'; }
val=$(escape_sed_repl "$user_value")
sed -i "s|^PASSWORD=.*|PASSWORD=${val}|" app.env

For structured files, prefer a structural tool: yq -i '.spec.template.spec.containers[0].image = strenv(IMG)' for YAML, jq for JSON.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq