tags:

views:

58

answers:

4

I tried the '/pat1/,/pat2/p', but I want to print only the text between the patterns, not the whole line. How do I do that?

A: 

I don't know the kind of pattern you used, but i think it is also possible with regular expressions.

cat myfile | sed -r 's/^(.*)pat1(.*)pat2(.*)$/\2/g'
Till
useless use of cat.
ghostdog74
There's no need to capture the first and last groups.
Dennis Williamson
A: 

you can use awk.

$ cat file
other TEXT
pat1  text  i want pat2
pat1 TEXT I
WANT
pat2
other text
$ awk -vRS="pat2" 'RT{gsub(/.*pat1/,"");print}' file
  text  i want
 TEXT I
WANT

The solution works for patterns that span multiple lines

ghostdog74
+1  A: 

sed -r 's/pat1(.*)pat2/\1/g' somefile.txt

Johnsyweb
You need to escape the parentheses or use the `-r` option.
Dennis Williamson
Thanks, edited.
Johnsyweb
+1  A: 

A pattern range is for multiline patterns. This is how you'd do that:

sed  -n '/pat1/,/pat2/{/pat1\|pat2/!p}' inputfile
  • -n - don't print by default
  • /pat1/,/pat2/ - within the two patterns inclusive
  • /pat1\|pat2/!p - print everything that's not one of the patterns

What you may be asking for is what's between two patterns on the same line. One of the other answers will do that.

Edit:

A couple of examples:

$ cat file1
aaaa bbbb cccc
123 start 456
this is what
I want
789 end 000
xxxx yyyy zzzz
$ sed  -n '/start/,/end/{/start\|end/!p}' file1
this is what
I want

You can shorten it by telling sed to use the most recent pattern again (//):

$ sed  -n '/.*start.*/,/^[0-9]\{3\} end 0*$/{//!p}' file1
this is what
I want

As you can see, I didn't have to duplicate the long, complicated regex in the second part of the command.

Dennis Williamson
hmm, does that work? i thought its more appropriate to replace `pat[12]` instead of using `!p`. That is of course, if i don't misunderstand OP's requirement. :)
ghostdog74
@ghostdog74: I think the OP is using the wrong form (the one I have in my answer) to do what he wants. My last paragraph addresses that. Your answer addresses both forms. I'll add an example or two.
Dennis Williamson
@dennis. thanks for the edit. What about when the start and end pattern happens to be on the same line? Eg `start this is text i want end`. Although OP did not show a sample of his file, i am guessing he might have both patterns on the same line.
ghostdog74