How to replace string and its all occurrence with another string using bash
Contents
Bash supports number of string manipulation operations. It is providing the option to replace the given string to another string. String replacement using another string is commonly required in string processing and shell scripting program.
Syntax for replace string using Bash shell script
1 |
${input_string//old_string/new_string} |
Example 1: Replace the string in Bash
1 2 3 4 5 6 |
#!/bin/bash #Replace string and its all occurrence with another string Input_string='Cloud storage is getting popular in recent days. It is useful for the small companies.' Output_string=${Input_string//is/was} echo "Input String is : ${Input_string}" echo "Output String is : ${Output_string}" |
In this example, we are going to replace the string ‘is’ to ‘was’ using bash shell script. The input string is assigned to Input_String variable. Then we are replace the string ‘is’ to ‘was’ and store it in the Output_string variable. Lets run the shell script and see the output as below.
Output
1 2 |
Input String is : Cloud storage is getting popular in recent days. It is useful for the small companies. Output String is : Cloud storage was getting popular in recent days. It was useful for the small companies. |
Example 2 : Replace the string with single quotes
Here we are replacing = (equal) character with =’ (equal with single quotes) characters. \(backlash) is used to escape single quote that represent it as single quote character instead of string or command opening and closing character.
1 2 |
Given input ==> dt=20190909/hr=23 Target output ==> dt='20190909' AND hr='23' |
we used single quote to cover input string that avoid misinterpretation of special characters by shell.
1 2 3 4 5 6 7 |
#!/bin/bash #Replace string and its all occurrence with another string Input_string='dt=20190909/hr=23' temp_string=${Input_string//=/=\'} echo "Temporary String is : ${temp_string}" Final_string=${temp_string//\//\' AND }\' echo "Final String is : ${Final_string}" |
Output
1 2 |
Temporary String is : dt='20190909/hr='23 Final String is : dt='20190909' AND hr='23' |
Recommended Articles
- How to append Timestamp to file name in Shell script?
- How to parse input arguments with tokens in Bash script?
- How to redirect the output to a file in Linux?