I want to display all the characters in a file between strings "xxx" and "yyy" (the quotes are not part of the delimiters). How can I do that ? For example, if i have input "Hello world xxx this is a file yyy", the output should be " this is a file "
You can use the pattern matching flag in
So
Finally the remembered string is printed. |
|||||
|
The question is only interesting if the delimiters are not necessarily on the same line. It can be done several ways (even with #!/bin/sh awk ' BEGIN { found = 0; } /xxx/ { if (!found) { found = 1; $0 = substr($0, index($0, "xxx") + 3); } } /yyy/ { if (found) { found = 2; $0 = substr($0, 0, index($0, "yyy") - 1); } } { if (found) { print; if (found == 2) found = 0; } } ' This is tested lightly for the cases where at most one substring is on a line, using this data: this is xxx yy first second yyy xxx.x yyy xxx#yyy and this output (script is "foo", data is "foo.in"): $ cat foo.in|./foo yy first second .x # The way it works, is that the input data is in By the way, this example would not work for
since it checks only the first match. The Perl script will give different results, since it uses a greedy match rather than the index/substr which I used in the awk example. Perl, of course, can do the same -- with a script. Awk (like Perl) is free-format, so one could express the command as something like
but that is rarely done, except for the sake of example. Likewise, Further reading: |
|||||
|
This should do what you are trying to do :
This assumes both delimiter strings are on the same line |
|||||||||||||||||
|
A solution that also works when Not exactly pretty... The
|
||||
|
Here is a solution with python :
Save this script as a file "post.py" and launch it with: python post.py your_file_to_search_in.txt The script compiles a regular expression and print all occurences found in the text of the file. (?:.|\n) is a non capturing group matching any character including newline Edit : solution improved thanks to 1_CR tips :
|
|||||||||
|
pcregrep -Mo '(?<=STRING1)(\n|.)*?(?=STRING2)' infile
– don_crissti Mar 31 at 21:33