0

I have a line like this

BR_MALLOC %p File - %s, Func - %s, Line - %u\n

This is actually a line from a C program which outputs the malloced address, the file where the custom malloc BR_MALLOC was called etc etc.

Now, I am running sed on this output to get just the malloced address (%p)

I tried this regular expression

$ echo "BR_MALLOC %p File - %s, Func - %s, Line - %u\n" | sed 's/BR_MALLOC\s+\(\S+\).*/\1'

Expected Output

%p

Output I get is

BR_MALLOC %p File - %s, Func - %s, Line - %un

Where am I going wrong?

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125

2 Answers2

1

You might need to escape the + (docs):

echo "BR_MALLOC %p File - %s, Func - %s, Line - %u\n" | sed 's/BR_MALLOC\s\+\(\S\+\).*/\1/'
%p
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Can you explain why you added a `?` and also what is the greedy matching you are referring to? – Pavan Manjunath Jun 11 '12 at 13:18
  • I tried your suggestion, I am getting this error `sed: -e expression #1, char 28: invalid reference \1 on `s' command's RHS`. If I take off `-r` my old ouput occurs. ie `?` has no effect :( – Pavan Manjunath Jun 11 '12 at 13:20
  • If you're sure you copied and pasted correctly, then our versions of `sed` behave differently. Try escaping the parantheses as `\(` and `\)` (it's not needed on my GNU sed version 4.2.1). – Lev Levitsky Jun 11 '12 at 13:27
  • @Stacker sorry, my original answer was wrong, the issue is not about greediness. However, you still might want to get familiar with the concept, so: look [here](http://www.regular-expressions.info/repeat.html). However, `sed` seems to only support greedy matching (see [this question](http://stackoverflow.com/questions/1103149/non-greedy-regex-matching-in-sed)). – Lev Levitsky Jun 11 '12 at 13:45
1

Don't know about sed, but with perl your expression would work pretty much as is:

perl -pe 's/BR_MALLOC\s+(\S+).*/$1/'
Qtax
  • 33,241
  • 9
  • 83
  • 121