NewKidOnTheBlock
NewKidOnTheBlock

Reputation: 75

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

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

Answers (3)

oguz ismail
oguz ismail

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

Wiktor Stribiżew
Wiktor Stribiżew

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

Cyrus
Cyrus

Reputation: 88626

With a conditional jump (t) to label 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.

Upvotes: 0

Related Questions