How to search a file for a pattern and get a new file from the match point to end of file?
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开发者_JAVA技巧 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.
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.
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
精彩评论