Reputation: 75
Input:
i="Item1;Item2;Item3;;;;;;;;"
Desired output:
i="Item1;Item2;Item3"
How do I get rid of the last few semicolons?
I know this one way to do it using 'sed':
sed 's/;$//'
However, it only removes the last semicolon. Running it repeatedly doesn't seem practical.
Upvotes: 3
Views: 877
Reputation: 50750
You don't need external utilities for this.
$ input='Item1;Item2;Item3;;;;;;;;'
$ echo "${input%"${input##*[!;]}"}"
Item1;Item2;Item3
Or, using extended globs:
$ shopt -s extglob
$ echo "${input%%*(;)}"
Item1;Item2;Item3
Upvotes: 5
Reputation: 626835
You can use
sed 's/;*$//'
The main point here is to add the *
quantifier (that means zero or more) after ;
to make the regex engine match zero or more semi-colons.
Synonymic sed
commands can look like
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"
Upvotes: 3
Reputation: 88626
With a conditional jump (t
) to label a
:
i="Item1;Item2;Item3;;;;;;;;"
sed ':a; s/;$//; ta' <<< "$i"
t label
: If as///
has done a successful substitution since the last input line was read and since the lastt
orT
command, then branch to label.
Upvotes: 0