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

Remove sequence of a specific character from the end of a string in Bash

输入:

i="Item1;Item2;Item3;;;;;;;;"

期望的输出:

i="Item1;Item2;Item3"

如何去掉最后几个分号?

我知道使用 'sed' 的一种方法:

sed 's/;$//'

但是,它只删除了最后一个分号。 运行 反复的好像不太实用

使用条件跳转 (t) 标签 a:

i="Item1;Item2;Item3;;;;;;;;"
sed ':a; s/;$//; ta' <<< "$i"  

t label: If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label.

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

$ input='Item1;Item2;Item3;;;;;;;;'
$ echo "${input%"${input##*[!;]}"}"
Item1;Item2;Item3

或者,使用扩展的 globs:

$ shopt -s extglob
$ echo "${input%%*(;)}"
Item1;Item2;Item3

您可以使用

sed 's/;*$//'

这里的要点是在;之后添加*量词(即零个或多个)以使正则表达式引擎匹配零或更多分号。

同义 sed 命令可以类似于

sed 's/;;*$//'    # POSIX BRE "one ; and then zero or more ;s at the end of string"
sed 's/;\+$//'    # GNU sed POSIX BRE "one or more semi-colons at the end of string"
sed -E 's/;+$//'  # POSIX ERE "one or more semi-colons at the end of string"