I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".
#!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" # do something...
The result must be like this:
firstString="I love Sara and Marry"
Replace String in a File with the `sed` Command'-i' option is used to modify the content of the original file with the replacement string if the search string exists in the file. 's' indicates the substitute command. 'search_string' contains the string value that will be searched in the file for replacement.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
$() – the command substitution. ${} – the parameter substitution/variable expansion.
To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}
:
#!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" echo "${firstString/Suzi/"$secondString"}" # prints 'I love Sara and Marry'
To replace all occurrences, use ${parameter//pattern/string}
:
message='The secret code is 12345' echo "${message//[0-9]/X}" # prints 'The secret code is XXXXX'
(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)
Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".
This can be done entirely with bash string manipulation:
first="I love Suzy and Mary" second="Sara" first=${first/Suzy/$second}
That will replace only the first occurrence; to replace them all, double the first slash:
first="Suzy, Suzy, Suzy" second="Sara" first=${first//Suzy/$second} # first is now "Sara, Sara, Sara"
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