Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression extract string after a colon in bash

Tags:

regex

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!

like image 998
prolink007 Avatar asked Sep 24 '12 16:09

prolink007


2 Answers

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)
like image 198
gvalkov Avatar answered Sep 22 '22 02:09

gvalkov


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

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

like image 44
Alex Merelli Avatar answered Sep 23 '22 02:09

Alex Merelli