Replace one substring for another string in shell script

前端 未结 10 1636
猫巷女王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:20

    Pure POSIX shell method, which unlike Roman Kazanovskyi's sed-based answer needs no external tools, just the shell's own native parameter expansions. Note that long file names are minimized so the code fits better on one line:

    f="I love Suzi and Marry"
    s=Sara
    t=Suzi
    [ "${f%$t*}" != "$f" ] && f="${f%$t*}$s${f#*$t}"
    echo "$f"
    

    Output:

    I love Sara and Marry
    

    How it works:

    • Remove Smallest Suffix Pattern. "${f%$t*}" returns "I love" if the suffix $t "Suzi*" is in $f "I love Suzi and Marry".

    • But if t=Zelda, then "${f%$t*}" deletes nothing, and returns the whole string "I love Suzi and Marry".

    • This is used to test if $t is in $f with [ "${f%$t*}" != "$f" ] which will evaluate to true if the $f string contains "Suzi*" and false if not.

    • If the test returns true, construct the desired string using Remove Smallest Suffix Pattern ${f%$t*} "I love" and Remove Smallest Prefix Pattern ${f#*$t} "and Marry", with the 2nd string $s "Sara" in between.

提交回复
热议问题