Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace "/" in a POSIX sh string

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?

like image 685
Anis_Stack Avatar asked Feb 20 '14 15:02

Anis_Stack


People also ask

How do you replace a word in a string in shell script?

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.

How do you replace a specific character in a string in Unix?

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.

How do you change a string in bash?

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.

How do you change a variable in Linux?

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”.


1 Answers

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')
like image 137
Charles Duffy Avatar answered Oct 03 '22 22:10

Charles Duffy