To replace substring in the bash string str
I use:
str=${str/$pattern/$new}
However, I'm presently writing a script which will be executed with ash
.
I have a string containing '/'
and I want to use the above syntax inorder to replace the '/'
in my string but it does not work.
I tried:
str=${str///a}
str=${str/\//a}
str=${str/'/'/a}
But they do not work
How I can fix that?
To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.
The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
The syntax to find and replace a variable value using SED is pretty much the same as replacing a string. We'll look at an example, now, to understand the implementation of the command. This SED command will find the variable “num1” and then will enter the new value as “200”.
This parameter expansion is a bash extension to POSIX sh. If you review the relevant section of IEEE standard 1003.1, you'll see that it isn't a required feature, so shells which promise only POSIX compliance, such as ash
, have no obligation to implement it, and no obligation for their implementations to hew to any particular standard of correctness should they do so anyhow..
If you want bash extensions, you need to use bash (or other ksh derivatives which are extended similarly).
In the interim, you can use other tools. For instance:
str=$(printf '%s' "$str" | tr '/' 'a')
or
str=$(printf '%s' "$str" | sed -e 's@/@a@g')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With