Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - how to do regex groups using sed

Tags:

regex

linux

sed

Is there anyway you can do regex match group using sed like java regex pattern/match/group?

if i have string like

test-artifact-201251-balbal-0.1-SNAPSHOT.jar 

how do I use sed just to get the result like:

test-artifact-0.1-SNASHOT.jar 

I am wondering does sed allow you to do something like java regex, you define the pattern like:

([a-z]*-[a-z]*-)([0-9]*-)([a-z]*-)([.]*SNAPSHOT.jar) 

and then you can get the results as an array like:

test-artifact- 201251- balbal- 0.1-SNAPSHOT.jar 
like image 625
Shengjie Avatar asked Jul 25 '12 13:07

Shengjie


People also ask

How do you use groups in sed?

Grouping can be used in sed like normal regular expression. A group is opened with “\(” and closed with “\)”. Grouping can be used in combination with back-referencing. Back-reference is the re-use of a part of a Regular Expression selected by grouping.

Can you use regex in sed?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).

How does regex group work?

What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.


1 Answers

You have to escape parentheses to group expressions:

\([a-z]*-[a-z]*-\)\([0-9]*-\)\([a-z]*-\)\([.]*SNAPSHOT.jar\) 

And use them with \1, \2, etc.


EDIT: Also note just before SNAPSHOT that [.] will not match. Inside brackets . is literal. It should be [0-9.-]*

like image 63
Birei Avatar answered Sep 22 '22 07:09

Birei