Bash:根據條件刪除花括號

Bash:根據條件刪除花括號

我想從下面的字串中刪除大括號,但前提是 * 在它們之間找到大括號。

我在這個主題上找到了很多答案,但在我的場景中,我只想刪除那些滿足條件的大括號,即{*} --> *.

name,apple,price,{50 70 80 80},color,{*}
name,orange,price,{*},color,{80 30 40}

預期輸出:

name,apple,price,{50 70 80 80},color,*
name,orange,price,*,color,{80 30 40}

請幫忙,提前致謝。

答案1

使用sed'ss指令(如替代) - 在 中包含大括號regexp,但不在 中replacement

sed 's/{\*}/*/g'

答案2

只需 bash

line='name,orange,price,{*},color,{80 30 40}'
s='{*}'
echo "${line//"$s"/*}"
name,orange,price,*,color,{80 30 40}

我不知道如何進行轉義,以便s不需要該變數。

請注意,雙引號是必需的,否則您會得到:

$ echo "${line//$s/*}"
name,orange,price,*

答案3

命令

sed "/{\*}/s/{\*}/*/g" filename

輸出

name,apple,price,{50 70 80 80},color,*
name,orange,price,*,color,{80 30 40}

方法2

awk '$0 ~ "{*}" {gsub (/{\*}/,"*",$0);print }'  filename

輸出

name,apple,price,{50 70 80 80},color,*
name,orange,price,*,color,{80 30 40}

相關內容