Home > Software engineering >  How to use sed to extract a string using a string as search parameter
How to use sed to extract a string using a string as search parameter

Time:04-14

I am trying to return a string that is constantly changing via the output. I decided grep and sed might be the best way to handle this. Basically the output renders a large field of text that contains something to the effect of

https://rancher.website.com/version1/proj/abcd123?somethingsomethingsomethingetc

the goal is to return the FIRST instance of

https://rancher.website.com/version1/proj/

as there are multiple, and then return the contents of abcd123 up to the ? symbol before it.

I keep trying to tweak the sed command but keep running into errors with my syntax and I am having trouble wrapping my mind around the explanations given so far. I think one of my problems might be around the fact that the sed "search" for lack of a better term, is being run against a string rather than a single character. Also the forward slashes are a problem as I think those are being interpreted as operators in the sed command?

Command I am trying to use is more or less:

grep 'https://rancher.website.com/version1/projects/' grep.txt | sed 's/^.*'https:\/\/rancher.website.com\/version1\/projects\/'//g'

With grep.txt being the container for the output text of the initial command

CodePudding user response:

Replace everything up to the last / and everything from ? with empty strings.

grep -m 1 'https://rancher.website.com/version1/projects/' grep.txt | 
    sed -e 's#.*/##' -e 's#\?.*##'

When the pattern includes /, use a different character as the s delimiter to avoid having to escape it; I've used # above.

  • Related