-2

I can't seem to get the needed string with sed. Can someone help me see my error? I have tried so many combinations, but no luck. I know it has to be simple, but I'm at my wits' end.

echo '/documents/types/count/%5B%22cast%20arinfo%22%5D' | sed -En "s/(.*)%.*/\1/p"

Expected result:

/documents/types/count/
2
  • 1
    Like this? echo '/documents/types/count/%5B%22cast%20arinfo%22%5D' | sed "s/%.*//" Commented Apr 29 at 21:56
  • 1
    assuming var='/documents/types/count/%5B%22cast%20arinfo%22%5D' then parameter substitution would also work, eg: "${var%%\%*}" though bash appears to be smart enough to know that a 3rd % is a literal so "${var%%%*}" also works Commented Apr 29 at 22:21

1 Answer 1

2

The . in .* matches any character including % so it'll match up until the last % on the line. To match up until the first % on the line you'd need to match any non-% character instead which would be:

sed -En 's/([^%]*)%.*/\1/p'

but you could have made that more concise with:

sed 's/%.*//'

Realistically, though, if you're going to use an external tool for this, this is the job that cut exists to do:

cut -d'%' -f1

Regarding your use of double quotes in sed -En "s/(.*)%.*/\1/p" - in shell you should always use single quotes around every string (including scripts) until you need double quotes or no quotes, see https://mywiki.wooledge.org/Quotes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.