prolink007
prolink007

Reputation: 34534

regular expression extract string after a colon in bash

I need to extract the string after the : in an example below:

package:project.abc.def

Where i would get project.abc.def as a result.

I am attempting this in bash and i believe i have a regular expression that will work :([^:]*)$.

In my bash script i have package:project.abc.def as a variable called apk. Now how do i assign the same variable the substring found with the regular expression?

Where the result from package:project.abc.def would be in the apk variable. And package:project.abc.def is initially in the apk variable?

Thanks!

Upvotes: 11

Views: 17428

Answers (3)

gvalkov
gvalkov

Reputation: 4097

There is no need for a regex here, just a simple prefix substitution:

$ apk="package:project.abc.def"
$ apk=${apk##package:}
project.abc.def

The ## syntax is one of bash's parameters expansions. Instead of #, % can be used to trim the end. See this section of the bash man page for the details.

Some alternatives:

$ apk=$(echo $apk | awk -F'package:' '{print $2}')
$ apk=$(echo $apk | sed 's/^package://')
$ apk=$(echo $apk | cut -d':' -f2)

Upvotes: 16

Alex Merelli
Alex Merelli

Reputation: 41

$ string="package:project.abc.def"
$ apk=$(echo $string | sed 's/.*\://')

".*:" matches everything before and including ':' and then its removed from the string.

Upvotes: 4

chepner
chepner

Reputation: 531055

Capture groups from regular expressions can be found in the BASH_REMATCH array.

[[ $str =~ :([^:]*)$ ]]
# 0 is the substring that matches the entire regex
# n > 1: the nth parenthesized group
apk=${BASH_REMATCH[1]}

Upvotes: 2

Related Questions