LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   delete a line containing a pattern and the next line of a text file (https://www.linuxquestions.org/questions/programming-9/delete-a-line-containing-a-pattern-and-the-next-line-of-a-text-file-524497/)

powah 01-31-2007 05:13 PM

delete a line containing a pattern and the next line of a text file
 
How to delete a line containing a pattern and the next line of a text file?
Any programming language is ok.
Thanks.
e.g.
Delete the line containing the "PRE-AUTHORIZED PAYMENT" and the next (adjacent) line.
Input:
Dec. 29, 2006 Jan. 02, 2007
THE BRICK WAREHOUSE L.P
$632.70
Dec. 29, 2006 Dec. 29, 2006 PRE-AUTHORIZED PAYMENT
$1,291.95
Dec. 31, 2006 Jan. 02, 2007
PRODUCE DEPOT
$33.83

Output:
Dec. 29, 2006 Jan. 02, 2007
THE BRICK WAREHOUSE L.P
$632.70
Dec. 31, 2006 Jan. 02, 2007
PRODUCE DEPOT
$33.83

wjevans_7d1@yahoo.co 01-31-2007 05:24 PM

Perl is excellent for simple stuff like this. (grin)

You could probably do it like this:

Open the input file, and open an output file. Copy each line from input to output. Keep a line number for each input line; it would be 1 for the first line, 2 for the second, and so on. If an input line contains the pattern of interest, set another variable (let's call it $elephant) equal to the current line number; otherwise, leave $elephant alone. Then, before you output the current line, compare the current line number with $elephant. If it's equal to $elephant, or equal to $elephant+1, don't output this line.

For this to work, you'll need to set $elephant to something like -1 at the beginning; otherwise, the first line will not be output because the line number will be 1 and $elephant will be 0.

If you're not familiar with Perl, http://perldoc.perl.org is your friend. In particular, I'd recommend you visit:

http://perldoc.perl.org/index-overview.html
http://perldoc.perl.org/index-tutorials.html
http://perldoc.perl.org/index-faq.html

And when you're ready to eat the whole enchilada:

http://perldoc.perl.org/index-language.html

Hope this helps.

matthewg42 01-31-2007 05:28 PM

Without changing original file:
Code:

sed '/PRE-AUTHORIZED PAYMENT/,+1 d' input_file > new_file
Or, in place editing:
Code:

sed -i '/PRE-AUTHORIZED PAYMENT/,+1 d' input_file
Sed is your friend.

colucix 01-31-2007 05:34 PM

Code:

gawk '/PRE-AUTHORIZED PAYMENT/ {getline ; getline}{print $0}' filename > new_filename
gawk is a good friend, too! :)


All times are GMT -5. The time now is 12:45 AM.