Replace one substring for another string in shell script

前端 未结 10 1375
猫巷女王i
猫巷女王i 2020-11-22 11:55

I have \"I love Suzi and Marry\" and I want to change \"Suzi\" to \"Sara\".

#!/bin/bash
firstString=\"I love Suzi and Marry\"
secondString=\"Sara\"
# do some         


        
相关标签:
10条回答
  • 2020-11-22 12:24

    To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}:

    #!/bin/bash
    firstString="I love Suzi and Marry"
    secondString="Sara"
    echo "${firstString/Suzi/$secondString}"    
    # prints 'I love Sara and Marry'
    

    To replace all occurrences, use ${parameter//pattern/string}:

    message='The secret code is 12345'
    echo "${message//[0-9]/X}"           
    # prints 'The secret code is XXXXX'
    

    (This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)

    Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".

    0 讨论(0)
  • 2020-11-22 12:25

    If tomorrow you decide you don't love Marry either she can be replaced as well:

    today=$(</tmp/lovers.txt)
    tomorrow="${today//Suzi/Sara}"
    echo "${tomorrow//Marry/Jesica}" > /tmp/lovers.txt
    

    There must be 50 ways to leave your lover.

    0 讨论(0)
  • 2020-11-22 12:26

    try this:

     sed "s/Suzi/$secondString/g" <<<"$firstString"
    
    0 讨论(0)
  • 2020-11-22 12:30

    Since I can't add a comment. @ruaka To make the example more readable write it like this

    full_string="I love Suzy and Mary"
    search_string="Suzy"
    replace_string="Sara"
    my_string=${full_string/$search_string/$replace_string}
    or
    my_string=${full_string/Suzy/Sarah}
    
    0 讨论(0)
提交回复
热议问题