Essentially what I am trying to do is take a string with a bunch of text and if it has a substring of "$$" to replace it with a substring of "$$$"
ex:
string="abcde\$\$fghi"
# Modify string
echo $string
# ^ should give "abcde$$$fghi"
I have been at this for like 2 hours now and it seems like a very simple thing, so if anyone could provide some help then I would greatly appreciate it. Thanks!
EDIT: Changed original string in the question from "abcde$$fghi"
to "abcde\\$\\$fghi"
$$
is a special variable in the shell, it contains the ID of the current process. The variables are expanded in double quotes, therefore string
does not contain $$
but a number (the PID of shell) instead.
Enclose the string in apostrophes (single quotes) to get $$
inside it.
The replacement you need can be done in multiple ways. The simplest way (probably) and also the fastest way (for sure) is to use /
in the parameter expansion of $string
:
echo "${string/'$$'/'$$$'}"
To make it work you have to use the same trick as before: wrap $$
and $$$
in single quotes to prevent the shell replace them with something else. The quotes around the entire expression are needed to preserve the space characters contained by $string
, otherwise the line is split to words by whitspaces and and echo
outputs these words separated by one space character.
Check it online .
If you quote the string with single quote marks (ie string='abcde$$fghi'
) you can do the replacement with echo "${string/'$$'/'$$$'}"
Edit: this is basically what @axiac said in their comment
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.