Search & Replace
In this page:
Replacing the First Occurrence
${s/old/new} searches the string for old and replaces only the first match it finds with new, leaving any later occurrences untouched. This is the single-slash form of search-and-replace parameter expansion.
Example: Replacing the First Occurrence
#!/bin/bash
text="cat sat on the cat mat"
result=${text/cat/dog}
echo "$result"
Login to try C/C++/Java/PHP code in the editor
Replacing All Occurrences
${s//old/new} (with a double slash) replaces every occurrence of old throughout the string, not just the first one. This is the go-to form when you want a global find-and-replace.
Example: Replacing All Occurrences
#!/bin/bash
text="cat sat on the cat mat"
result=${text//cat/dog}
echo "$result"
Login to try C/C++/Java/PHP code in the editor
Anchoring to Start or End
${s/#old/new} only replaces old if it matches starting at the very beginning of the string, and ${s/%old/new} only replaces it if it matches ending at the very end of the string. This is useful for trimming or fixing a prefix/suffix without accidentally touching a matching substring in the middle.
Example: Anchoring to Start or End
#!/bin/bash
filename="test_test_file"
start_replaced=${filename/#test_/demo_}
echo "Start replaced: $start_replaced"
end_replaced=${filename/%file/data}
echo "End replaced: $end_replaced"
Login to try C/C++/Java/PHP code in the editor
Deleting Matches by Replacing With Nothing
Leaving out the replacement text entirely, ${s//old/}, effectively deletes every occurrence of old from the string since it's being replaced with an empty string. This is a quick way to strip out unwanted characters or substrings.
Example: Deleting Matches by Replacing With Nothing
#!/bin/bash
phone="555-123-4567"
digits_only=${phone//-/}
echo "Digits only: $digits_only"
Login to try C/C++/Java/PHP code in the editor
- Using
${s/old/new}when you meant to replace every occurrence; single-slash replaces only the *first* match, you need the double-slash${s//old/new}for all occurrences. - Assuming
oldin${s/old/new}is a regular expression; it's actually a glob-style pattern (like incaseor[[ == ]]), not a full regex. - Forgetting that
${s/#old/new}anchors the match to the start of the string and${s/%old/new}anchors it to the end -- without those anchors, the match can occur anywhere in the string.
${s/old/new}replaces only the first occurrence ofoldwithnew.${s//old/new}replaces every occurrence ofoldwithnew.${s/#old/new}replacesoldonly if it matches at the very start of the string;${s/%old/new}only if it matches at the very end.- The pattern side supports glob wildcards (
*,?,[...]), not full regular expression syntax.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: