Reputation: 53
I have a string in this format:
'abc pqr$v_val xyz'.
How can I replace $
with \$$
? I want my final output to be:
'abc pqr\$$v_val xyz'
Upvotes: 0
Views: 100
Reputation: 1596
input="a\$b" #input is a$b
dollar="\$"
doubleDollar="\\\$\$"
output="${input/$dollar/$doubleDollar}"
echo $output #a\$$b
Upvotes: 1
Reputation: 1
If you are using perl, following code will just do fine .
$str1 = 'abc pqr$v_val xyz' ;
$str1 =~ s/\$/\\\$\$/g ;
In case you are using Shell and the value stored in a shell variable you can use the sed to same effect !
Upvotes: 0
Reputation: 30850
As you haven't shown us where your input string is, I'll show two possibilities:
It's in a Bash variable (let's say $foo
). Then we can substitute as we expand:
echo "${foo//$/'\$$'}"
Note that we have to quote the replacement, so the shell doesn't substitute $$
with the process ID.
It's input from a file or other stream. Then we can use sed
as a filter:
sed -e 's/\$/\\$$/g'
Here, we need to escape $
in the pattern (because $
matches end-of-line in a regexp) but not in the replacement.
Note: both of these replace all $
from the input; if you only want to replace the first occurrence, you need to use /
instead of //
in the first example, or omit g
from the second example.
Upvotes: 0
Reputation: 4112
Try this:
echo 'abc pqr$v_val xyz' | sed 's/\$/\\\$\$/g'
eg:
user@host:/tmp$ echo 'abc pqr$v_val xyz' | sed 's/\$/\\\$\$/g'
abc pqr\$$v_val xyz
to assign variable;
#!/bin/bash
var=$(echo 'abc pqr$v_val xyz' | sed 's/\$/\\\$\$/g')
#var=`echo 'abc pqr$v_val xyz' | sed 's/\$/\\\$\$/g'` # you can also use this
echo $var
Eg:
user@host:/tmp$ ./test.sh
abc pqr\$$v_val xyz
Upvotes: 2