Search और Replace
In this page:
${string/old/new}
${string//old/new}
${string/#old/new}
${string/%old/new}
पहली Occurrence Replace करना
${s/old/new} string में old search करता है और सिर्फ पहले match को new से replace करता है, बाद की किसी भी occurrences को untouched छोड़ते हुए। यह search-and-replace parameter expansion का single-slash form है।
उदाहरण: 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
सभी Occurrences Replace करना
${s//old/new} (double slash के साथ) पूरी string में हर occurrence of old को replace करता है, सिर्फ पहले को नहीं। यह go-to form है जब आपको एक global find-and-replace चाहिए।
उदाहरण: 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
Start या End पर Anchoring करना
${s/#old/new} सिर्फ old को replace करता है अगर यह string की बिल्कुल शुरुआत से match करे, और ${s/%old/new} सिर्फ इसे replace करता है अगर यह बिल्कुल end पर match करके खत्म हो।
यह बिना गलती से बीच में एक matching substring को touch किए एक prefix/suffix trim या fix करने के लिए उपयोगी है।
उदाहरण: 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
कुछ भी ना के साथ Replace करके Matches Delete करना
Replacement text पूरी तरह छोड़ देना, ${s//old/}, effectively string से हर occurrence of old delete करता है क्योंकि यह एक empty string से replace हो रहा है। Unwanted characters या substrings strip करने का यह एक quick तरीका है।
उदाहरण: 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
${s/old/new}उपयोग करना जब आपका मतलब हर occurrence replace करना था; single-slash सिर्फ *पहला* match replace करता है, सभी occurrences के लिए आपको double-slash${s//old/new}चाहिए।- यह मान लेना कि
${s/old/new}मेंoldएक regular expression है; यह असल में एक glob-style pattern है (जैसेcaseया[[ == ]]में), पूरी regex नहीं। - यह भूल जाना कि
${s/#old/new}match को string की शुरुआत से anchor करता है और${s/%old/new}इसे end से anchor करता है -- उन anchors के बिना, match कहीं भी हो सकता है।
${s/old/new}सिर्फoldकी पहली occurrence कोnewसे replace करता है।${s//old/new}oldकी हर occurrence कोnewसे replace करता है।${s/#old/new}oldको सिर्फ तब replace करता है अगर यह string की बिल्कुल शुरुआत में match करे;${s/%old/new}सिर्फ तब अगर यह बिल्कुल end में match करे।- Pattern side glob wildcards (
*,?,[...]) support करता है, पूरी regular expression syntax नहीं।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: