如何在文件中搜索模式并从匹配点到文件末尾获取新文件?

发布于 2024-09-02 17:36:04 字数 219 浏览 3 评论 0原文

我需要获取一个文件并找到第一次出现的文字字符串模式作为文件的完整行:

Acknowledgments:

然后我希望从匹配行一直到文件末尾创建一个新文件。

我希望 Perl 是一个很好的方法来做到这一点,但我不是一个很好的 Perl 人,或者也许 sed 是一个好方法?

请建议一种在 Unix 中可靠地完成此操作的简单方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恏ㄋ傷疤忘ㄋ疼 2024-09-09 17:36:04

这是使用 sed 执行此操作的一种方法:

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

-n 选项禁止将输入打印到输出。 /^Acknowledgements:$/,$ 部分是一个地址范围规范,表示从与正则表达式 ^Acknowledgements:$ 匹配的行到末尾进行匹配。文件 ($),然后将这些行打印 (p) 到输出。

如果你希望输入文件和输出文件相同,你还需要指定-i选项来告诉sed进行就地编辑。

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.

嗳卜坏 2024-09-09 17:36:04

Perl

这是一个应该可以实现您想要的效果的脚本。

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;

下面是等效的 Perl 一行代码:

perl -ne 'print if /^Acknowledgments$/ .. 0' inputFile > outputFile

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文