0

Input:

get \tag-start Snooby ~p snoopy \tag-end please

Output: Snooby (after the tag and before ~p; non-greedy capture because some sentences contain several tags)

echo 'get \tag-start Snooby ~p snoopy \tag-end please' | sed 's/.*tag-start \(.*?\) ~p.*/\1/'

I don't know where goes wrong but this regex doesn't work to extract info in this case.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Luca
  • 59
  • 4

2 Answers2

0

Non-greedy is not supported by most sed implementations (I vaguely remember one implementation allowing PCRE)

As mentioned by Wiktor Stribiżew in comments, either of these would work for given case

$ sed 's/.*tag-start \(.*\) ~p.*/\1/' ip.txt
Snooby
$ sed 's/.*tag-start \([^~]*\) ~p.*/\1/' ip.txt
Snooby


As linux is tagged, you might have GNU grep with PCRE, in which case you can use non-greedy regex as needed

$ grep -oP 'tag-start \K.*?(?= ~p)' ip.txt
Snooby
Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • No sed supports PCREs (presumably because the associated regexp engine is very inefficient - see https://swtch.com/~rsc/regexp/regexp1.html) and though grep has `-P` the providers warn us in the man page that it is "highly experimental" and users have reported core dumps when using it. – Ed Morton Jun 05 '18 at 13:45
  • the one remembered was [ssed](https://launchpad.net/ssed/) - it has PCRE features... yeah `grep -P` is mentioned as experimental but that's been in man page for long time, I've never had any issues with it.. there are significantly more outstanding issues with normal grep than PCRE(https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep) – Sundeep Jun 05 '18 at 14:42
  • nice link for regex comparison, will go through sometime.. PCRE is often better in speed performance with back-references.. for ex `([a-z]..)\1` .. as it supports plenty of features compared to ERE, it certainly would be inefficient in many cases.. – Sundeep Jun 05 '18 at 14:44
-1

Try this sed:

echo "get \tag-start Snooby ~p snoopy \tag-end please" |sed 's/.*tag-start \(.*\) ~p.*/\1/'

Output:

Snooby

User123
  • 1,498
  • 2
  • 12
  • 26