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.
More on Text processing: grep, sed, awk, cut, sort, uniq
What are the most useful `grep` flags?BeginnerWhat is the difference between basic, extended and Perl regular expressions in grep?IntermediateWhat are the core `sed` commands you use in automation?BeginnerWhy does `sed -i` behave differently on macOS and Linux?IntermediateWhat is the structure of an `awk` program?BeginnerHow do you count occurrences per key with `awk` associative arrays?Intermediate