Bootstrap
<FreeKB>
Home
About
Walkthroughs
Linux Commands
Profile
Sign in
Edit FreeKB
Tag
Article Title
Hidden Title
Category
<p>Let's say that foo contains a value of Hello World.</p> <pre> <code>foo="Hello World"</code></pre> <p> </p> <p>The <strong>sed</strong> command with the s (substitue) option can be used to performs a replacment in a <a href="http://www.freekb.net/Article?id=1850" target="_blank">file</a> or a variable.</p> <p>In this example, the text "Hello" will be replaced with the text "Hi". When the -i flag is not used, the change will not actually be made. In this way, this is a sort of test that can be used to see the change, but not commit the change.</p> <pre> <code>echo $foo | sed 's|Hello|Hi|' . . . Hi World</code></pre> <p> </p> <p>With this syntax, Hello will be replaced with Hi in the foo variable.</p> <pre> <code>foo=$( sed "s|Hello|Hi|" <<< "$foo" )</code></pre> <p> </p> <p>This does the same.</p> <pre> <code>foo=$( echo "$foo" | sed "s|Hello|Hi|" )</code></pre> <p> </p> <hr /> <p><strong>Replace multiple instances of a string (global)</strong></p> <p>If a variable contains more than one occurence of a string, the <span style="background-color:#EEEEEE">g</span> (global) option will need to be used to change every instance of the string. For example, let's say a foo contains the following text.</p> <pre> <code>foo=" Hello World Hello World Hello World"</code></pre> <p> </p> <p>If the <span style="background-color:#EEEEEE">g</span> (global) flag is not used, only the first instance of the word Hello will be changed.</p> <pre> <code>~]# echo $foo | sed 's/Hello/Hi/' Hi World Hello World Hello World</code></pre> <p> </p> <p>The <span style="background-color:#EEEEEE">g</span> (global) flag will change every instance of Hello to Hi.</p> <pre> <code>~]# echo $foo | sed 's/Hello/Hi/g' Hi World Hi World Hi World</code></pre> <p> </p> <hr /> <p><strong>Multiple different replacements</strong></p> <p>In this example, Hello becomes Hi and World becomes Earth, in a single inline command.</p> <pre> <code>echo $foo | sed 's|Hello|Hi|; s|World|Earth|' . . . Hi Earth</code></pre> <p> </p>
Update