Sascha
Sascha

Reputation: 430

How to remove characters before and including an underscore?

In bash scripting what's an efficient way to do the following please?

var="fooo_barrrr"

What is the best way to remove all characters before and including the '_' so that var becomes "barrrr" please?

Upvotes: 3

Views: 8265

Answers (2)

fedorqui
fedorqui

Reputation: 290455

Using Parameter Expansion:

$ var="fooo_barrrr"
$ echo ${var#*_}
barrrr

To change the var itself, var=${var#*_}.

Note this removes up to the first _:

$ var="fooo_barrr_r"
$ echo ${var#*_}
barrr_r

If you wanted to remove up to the last one, you would need to use ## instead:

$ var="fooo_barrr_r"
$ echo ${var##*_}
r

See some alternatives:

With sed:

$ sed 's/^[^_]*_//' <<< "foo_barrrr_r"
barrrr_r

With awk:

$ awk 'gsub(/^[^_]*_/,"")1' <<< "foo_barrrr_r"
barrrr_r

With grep:

$ grep -oP '[^_]*_\K.*' <<< "foo_barrrr_r"
barrrr_r

In all cases, to store the new value in the same var, do var=$(command <<< "$var").

Upvotes: 8

Maroun
Maroun

Reputation: 96016

Or, using grep:

echo fooo_barrrr | grep -oP '.*(?=_)'

To understand the meaning of each flag, use grep --help:

  • -P, --perl-regexp

    PATTERN is a Perl regular expression

  • -o, --only-matching

    show only the part of a line matching PATTERN

In order to avoid incorrect results when having more than two parts, you can use:

echo fooo_barrrr_xyz | grep -oP '.*?(?=_)' | head -1

Upvotes: 1

Related Questions