从 Bash 中的字符串末尾删除特定字符的序列

New*_*ock 3 bash sed

输入:

i="Item1;Item2;Item3;;;;;;;;"
Run Code Online (Sandbox Code Playgroud)

期望的输出:

i="Item1;Item2;Item3"
Run Code Online (Sandbox Code Playgroud)

如何去掉最后几个分号?

我知道使用“sed”来实现这一点的一种方法:

sed 's/;$//'
Run Code Online (Sandbox Code Playgroud)

但是,它仅删除最后一个分号。反复运行似乎不太实际。

ogu*_*ail 5

您不需要为此使用外部实用程序。

$ input='Item1;Item2;Item3;;;;;;;;'
$ echo "${input%"${input##*[!;]}"}"
Item1;Item2;Item3
Run Code Online (Sandbox Code Playgroud)

或者,使用扩展的 glob:

$ shopt -s extglob
$ echo "${input%%*(;)}"
Item1;Item2;Item3
Run Code Online (Sandbox Code Playgroud)