← Back to Bash Course | Chapter 5: Functions | Lesson 5 of 11

String में Replacement

String replacement एक story पर find-and-replace उपयोग करने जैसा है: पहला matching word swap करें, या double-slash way उपयोग करने पर उनमें से हर एक को swap करें।

In this page:

  1. String Replacement
Syntax
bash
${variable/pattern/replacement}     # first match
${variable//pattern/replacement}    # all matches

String Replacement

${variable/pattern/replacement} string में pattern का पहला match replace करता है, जबकि ${variable//pattern/replacement} हर match replace करता है।

यह simple substitutions के लिए sed से pipe करने का एक built-in alternative है। Patterns basic globbing support करते हैं, पूरी तरह regular expressions नहीं।

Note: Double-slash form उपयोग करें, ${var//old/new}, जब आपको सभी occurrences replace करनी हों, सिर्फ पहली नहीं।

उदाहरण: String Replacement

bash
#!/bin/bash
text="foo bar foo baz"
echo "${text/foo/qux}"
echo "${text//foo/qux}"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. ${str/a/b} उपयोग करना और सभी occurrences replace होने की उम्मीद करना, जब सिर्फ पहली होती है; ${str//a/b} उपयोग करें।
  2. यह उम्मीद करना कि original variable change हो जाएगा, जब यह सिर्फ एक नई value produce करता है।
  3. Pattern में special characters escape करना भूल जाना, जैसे /।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.