views:

49

answers:

2

I need to take a file and find the first occurrence of a literal string pattern as a complete line of the file:

Acknowledgments:

And then I wish to create a new file from the line of match all the way to the end of the file.

I expect perl is a good way to do this, but I'm not much of a perl person, alternatively maybe sed is a good way?

Please suggest a simple way to reliably accomplish this in Unix.

+5  A: 

Here's one way to do that using sed:

sed -n '/^Acknowledgements:$/,$p' input-file > output-file

The -n option suppresses the printing of the input to the output. The /^Acknowledgements:$/,$ part is an address range specification that says to match from the line that matches the regular expression ^Acknowledgements:$ through the end of the file ($), and then to print those lines out (p) to the output.

If you want the input file and the output file to be the same, you also need to specify the -i option to tell sed to edit in-place.

Adam Rosenfield
+3  A: 

Perl

Here is a script that should achieve what you're after.

use strict;
use warnings;

open my $input,  '<', 'inputFile.txt';   # Open handle to input file 
open my $output, '>', 'output.txt';      # Open handle to output file

while (<$input>) {

    next if /^Acknowledgments:$/ .. 0;

    chomp $_;
    print $output $_,"\n";
}

close $input;
close $output;

Below is the equivalent Perl one-liner:

perl -ne 'print if /^Acknowledgments$/ .. 0' inputFile > outputFile
Zaid
This flip-flop operator is *wicked*.
Zaid
Please edit so I can up vote, I accidentally undid and now I can't re-vote up.
WilliamKF
@Zaid Thanks!!!
WilliamKF