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

Time:10-12

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.

CodePudding user response:

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

CodePudding user response:

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"

CodePudding user response:

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.

  • Related