LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Is it possible to output 38 lines in between x & y on a text file? (https://www.linuxquestions.org/questions/linux-newbie-8/is-it-possible-to-output-38-lines-in-between-x-and-y-on-a-text-file-4175454804/)

juliej 03-20-2013 02:31 AM

Is it possible to output 38 lines in between x & y on a text file?
 
I'm using Debian, remote only access.
I have a long text file that I want to read/output to my console, but only the 38 lines that are between x and y.
The 'location' of these lines within the file might change but the lines themselves do not change.
Is there a command to output to my console only the 38 lines that is 'in between' these two lines:

%d blah blah blah%a
(38 lines of text here)
blah blah: %d

Thank you so much :)

RaviTezu 03-20-2013 03:02 AM

Hi juliej,

If i got you correct,
Quote:

grep "%d blah blah blah%a" <path_to_file_name> -A 38
Will return you the next 38 lines after the line %d blah blah blah%a in the file.

juliej 03-20-2013 03:26 AM

/me jumps up and hugs RaviTezu
thank you :) That is perfect!

I was over thinking it with the 'in between' hehe.

btw did I say THANK YOU :D

David the H. 03-20-2013 07:54 AM

Some other options:

Using gnu sed:
Code:

sed -n ' /pattern/,+38p' infile.txt
Using ed:
Code:

ed -s infile.txt <<<'/pattern/;+38p'
Only gnu sed has the "+n" address pattern. In ed, separating the two addresses with ';' makes the second address relative to the first address. If you use a comma it's relative the current line.


If you want to get the part between the two patterns, whatever the number of lines, and with or without the bracketing lines:

Code:

#includes bracketing lines:
sed -n '/pattern1/,/pattern2/p' infile.txt
ed -s infile.txt <<<'/pattern1/;/pattern2/p'


#excludes bracketing lines:
sed -n '/pattern1/,/pattern2/ {/pattern1\|pattern2/d;p}' infile.txt
ed -s infile.txt <<<'/pattern1/+1;/pattern2/-1p'

As you can see, ed is generally better when you have to deal with relative line positions. With sed you have to process the matched section to remove the lines you don't want.

Here are a few useful sed references:
http://www.grymoire.com/Unix/Sed.html
http://sed.sourceforge.net/grabbag/
http://sed.sourceforge.net/sedfaq.html
http://sed.sourceforge.net/sed1line.txt
http://www.catonmat.net/series/sed-one-liners-explained

How to use ed:
http://wiki.bash-hackers.org/howto/edit-ed
http://snap.nlc.dcccd.edu/learn/nlc/ed.html
(also read the info page)


All times are GMT -5. The time now is 09:42 AM.