Replace one substring for another string in shell script

前端 未结 10 1373
猫巷女王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".

提交回复
热议问题