Mike Andreasen
Mike Andreasen

Reputation: 379

Using sed to replace string matching regex with wildcards

I have a string I'm trying manipulate with sed

js/plex.js?hash=f1c2b98&version=2.4.23"

Desired output is

js/plex.js"

This is what I'm currently trying

sed -i s'/js\/plex.js[\?.\+\"]/js\/plex.js"/'

But it is only matching the first ? and returns this output

js/plex.js"hash=f1c2b98&version=2.4.23"

I can't see why this isn't working after a few hours

Upvotes: 0

Views: 503

Answers (2)

repzero
repzero

Reputation: 8402

perhaps

sed 's#\(js/plex.js?\)[^"]\+".*#\1#g'

..

\# is used as a delimiter

\(js/plex.js?\)[^"]\+".* #find this pattern and replace everything with your marked pattern \1 found

The marked pattern

In sed you can mark part of a pattern or the whole pattern buy using \( \). .

When part of a pattern is enclosed by brackets () escaped by backslashes..the pattern is marked/stored...

in my example this is my pattern without marking

js/plex.js?[^"]\+".*

but I only want sed to remember js/plex.js? and replace the whole line with only this piece of pattern js/plex.js? ..with sed the first marked pattern is known as \1, the second \2 and so forth

\(js/plex.js?\) ---> is marked as \1

Hence I replace the whole line with \1

Upvotes: 1

Ismail Moghul
Ismail Moghul

Reputation: 2974

This works

echo 'js/plex.js?hash=f1c2b98&version=2.4.23"' | sed  s:.js?.*:.js:g

With the original Regex:

Firstly I would suggest use a different delimiter (like : in sed when using / in the regex. Secondly, the use of [] means that you are matching the characters inside the brackets (and as such it will not expand the .+ to the end of the line - you could potentially try put the + after the [])

Upvotes: 1

Related Questions