在perl中删除行

发布于 2024-12-15 23:16:30 字数 314 浏览 0 评论 0原文

我是 Perl 新手,以前没有任何其他编程语言的编程经验。我正在尝试使用 do-while 循环删除/跳过几行。我正在尝试删除/跳过两个标签之间的数据:

代码:

if($work=/^<worker>/)
{
   do
       {
         delete $work[$i];
                  ++$i;
                     }
       print $work,"\n";
}

I am new to perl and have no previous programming experience with any other programming language. I am trying to delete/skip few line using a do-while loop. I am trying to delete/skip data between two tags: <worker> and </workers>.

Code:

if($work=/^<worker>/)
{
   do
       {
         delete $work[$i];
                  ++$i;
                     }
       print $work,"\n";
}

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

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

发布评论

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

评论(3

莳間冲淡了誓言ζ 2024-12-22 23:16:30

我假设您想跳过标签 之间的数据。你需要在正则表达式中使用 ..

这是一个单行代码可以做到这一点

perl -ne 'print unless /<workers>/../<\/workers>/' <file_name>

如果你想在脚本中执行它,请在从文件中读取一行后添加这一行

next if /<worker>/../<\/workers>/;

你可以用这个非常好的 演示,作者:brian d foy

I am assuming you want to skip data between tags <workers> and </workers>. You need to use .. in regular expression

This is a one liner that does it

perl -ne 'print unless /<workers>/../<\/workers>/' <file_name>

If you want to do it in the script, add this line after reading a line from the file

next if /<worker>/../<\/workers>/;

You can start perl with this very good presentation by brian d foy

ι不睡觉的鱼゛ 2024-12-22 23:16:30
while (<>) {
  print unless m|<worker>| .. m|</workers>|;
}

在不同的标签上开始和结束似乎有点奇怪。他们应该都是“工人”还是“工人”?

while (<>) {
  print unless m|<worker>| .. m|</workers>|;
}

Seems slightly strange to start and end on different tags. Should they both be 'worker' or 'workers'?

羁拥 2024-12-22 23:16:30

我假设您有如下数据:

my $x = <<END;

Text to keep
<worker> text to be deleted </worker>
Text to keep again
<worker>
Text to be deleted
</worker>
END

如果您还想删除 标签:

$x =~ s/<worker>.*?<\/worker>//g;

如果您需要保留标签:

$x =~ s/<worker>.*?<\/worker>/<worker><\/worker>/g;

但是,只有当您可以保证 < code>标签不嵌套。以下字符串将导致错误:

<worker> lalala <worker> bababa </worker> lalala </worker>

要真正好且安全地完成这项工作,您需要使用诸如 HTML::TreeBuilderXML::Twig 之类的解析模块

I assume you have data like:

my $x = <<END;

Text to keep
<worker> text to be deleted </worker>
Text to keep again
<worker>
Text to be deleted
</worker>
END

If you want to remove <worker></worker> tags as well:

$x =~ s/<worker>.*?<\/worker>//g;

If you need to keep tags:

$x =~ s/<worker>.*?<\/worker>/<worker><\/worker>/g;

However, this will work only if you can guarantee <worker> tags are not nested. Following string will cause error:

<worker> lalala <worker> bababa </worker> lalala </worker>

To do this work really good and safe you need to use parsing modules like HTML::TreeBuilder or XML::Twig

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