Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete everyting preceding and including a certain substring from variable

Tags:

bash

sed

cut

In Bash, how can I delete characters from a variable until a certain substring?

Example:

ananas1kiwi2apple1banana2tree

shall look like this:

apple1banana2tree

The substring in this case is 2.

like image 300
Anne K. Avatar asked Nov 09 '16 12:11

Anne K.


People also ask

How do I remove all text before after a specific character?

Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).

How do I extract text before and after a specific character in Excel?

To get text following a specific character, you use a slightly different approach: get the position of the character with either SEARCH or FIND, subtract that number from the total string length returned by the LEN function, and extract that many characters from the end of the string.


1 Answers

If you want to remove the substring upto 2, using bash parameter expansion:

${var#*2}
  • # does non-greedy match from left, use ## for greediness

  • #*2 matches and discards upto first 2 from variable var

Example:

$ var='ananas1kiwi2apple1banana2tree'
$ echo "${var#*2}"
apple1banana2tree
like image 57
heemayl Avatar answered Nov 02 '22 21:11

heemayl