Reputation: 33
The problem is there is a file with many strings like $VARx$
and x
stands for a number from 1 to 9: $VAR1$
, $VAR2$
, $VAR3$
, etc.
I want to quote these strings like $VARx$
→ "$VARx$"
. I read or know that this could be possible with sed out of the command line but I have no idea how. Something like that but don't work:
sed -i "s/\\\$VAR1\$/\"\$VAR1\"\$/g" file.txt
The special part would be to include the variable x
.
Upvotes: 0
Views: 76
Reputation: 3838
Another alternative using sed
:
sed -i 's/\(\$VAR[1-9]\$\)/"\1"/g' file.txt
This solution seems a bit closer to the PO's specification :
a file with many strings like
$VARx$
and x stands for a number from 1 to 9.
=> [1-9]
matches only one digit between 1 and 9.
In this example, I also wanted to show the use of capturing parentheses : \1
corresponds to the first expression captured by the capturing parentheses (\(...\)
). Of course, &
work as well for this case :
sed -i 's/\$VAR[1-9]\$/"&"/g' file.txt
Be careful: -i
will do the substitution directly into the file instead of standard output.
Upvotes: 2
Reputation: 15501
Try
sed -i 's/\$VAR[[:digit:]]\+\$/"&"/g' file.txt
[[:digit:]]\+
matches 1 or more digits.
&
represents the matching string.
GNU sed manual: http://www.gnu.org/software/sed/manual/html_node/index.html
Upvotes: 4