There are many questions asking about how to use a variable within a sed pattern, for example: sed "s/re/$VAR/" file
, but I want to perform a substitution on a variable. So far, I have been using echo
to do this:
echo "$VAR" | sed 's/re/new/'
But, though this works, it seems messy. Is there a simpler/more elegant way of doing this in bash or zsh?
If you don't want to use sed, you can use "parameter expansion" for search and replace within a parameter; quoting the Bash manual:
Parameter expansion is not limited to this kind of substitution, there are many more, see the manual.
A few examples
Leaving away quoting for readability.
Simple variables
Positional parameters
Arrays
Combinations
These can also be combined:
Extended pattern matching
Together with extended patterns, parameter expansion for search and replace becomes quite powerful:
The example is somewhat contrived as the same problem could be solved simpler – the point is that it's pretty flexible.
You can do it like this:
If you want to do that and update the variable you can do this: