LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   grep and store two lines in other file (http://www.linuxquestions.org/questions/linux-newbie-8/grep-and-store-two-lines-in-other-file-863036/)

jkeertir 02-16-2011 07:00 AM

grep and store two lines in other file
 
Dear all,

I have following contents

#1
aaaa
#2
bbb
#3
ccc

I want to grep "#2" and want the output as

#1
aaaa
#3
ccc

Please help me using shell script

With regards,
Keerti

AlucardZero 02-16-2011 07:06 AM

Code:

grep -vA1 "#2" foo.txt
Something like that?

macemoneta 02-16-2011 07:25 AM

This will do it:

Code:

grep -v "`grep -A1 '#2' filename`" filename

fordeck 02-16-2011 07:32 AM

If you want to store the output in a new file just add a redirection. For example using AlucardZero's code:

Code:

grep -vA1 "#2" foo.txt > newfile
Regards,

Fordeck

grail 02-16-2011 09:27 AM

Or if it doesn't have to be grep:
Code:

awk '/2/{getline;next}1' file

crts 02-16-2011 10:46 AM

Sed is another possibility to accomplish that:
Code:

sed -i '/^#2/ {N;d}' file

kurumi 02-16-2011 07:32 PM

Code:

$ ruby -ne 'gets && next if /^#2/;print ' file
#1
aaaa
#3
ccc



All times are GMT -5. The time now is 01:31 PM.