Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one substring for another string in shell script

Tags:

bash

shell

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" 
like image 833
Zincode Avatar asked Nov 03 '12 16:11

Zincode


People also ask

How do I replace a string with another string in Shell?

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.

How do you get and replace a substring from a string?

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.

What is $() in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


2 Answers

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

like image 91
ruakh Avatar answered Sep 19 '22 09:09

ruakh


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" 
like image 39
Kevin Avatar answered Sep 17 '22 09:09

Kevin