繁体   English   中英

如何使用Grep删除perl中行的特定结尾字?

[英]how to using Grep for remove the specific end word of line in perl?

我每天都会创建一个文件,我想删除结尾字符为utc并在perl中输出到其他文件的行,我尝试使用grep和regexp,但出现如下错误msg,

sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file

grep代码:

system("grep -v \"utc$ \" /doc/$date/before > /doc/$date/after");

该文件看起来像

config setting
^MMon Nov 13 10:45:52.401 utc   -->the line is I wnat to remove
start configuration...
clock timezone utc 8

有什么建议么? 我现在很乐意尝试任何事情。

没有必要去外部工具这样一个共同的任务。 它涉及启动一个shell和另一个程序,(正确地)转义一些东西。 它容易出错,效率低得多,并且在错误检查方面也较差。 为什么不在Perl程序中使用Perl?

读取文件并将其行写到新文件中,跳过不需要的文件。 例如,请参阅此帖子以获取详细信息。

这是使用Path :: Tiny的快速方法

use warnings;
use strict;

use Path::Tiny;

my $file     = '...';
my $new_file = '...';

my @new_lines = grep { not /utc\s*$/ } path($file)->lines; 

path($new_file)->spew(@new_lines);

模块的path($file)打开文件,而lines返回行列表; 它们由grep过滤,未以utc结尾(可能带有尾随空格)的@new_lines被分配给@new_lines

然后, spew方法将这些行写入$new_file

有关使用此模块“编辑”文件的几种(其他)方法,请参阅本文


一口气

perl -ne'print if not /utc\s*$/' file  > new_file

一个直接的答案可能最好地说明了使用外部命令的缺点。

我们需要通过shell传递一些特定的序列给grep ,这些序列将由Perl和shell或两者解释。 所以他们需要正确逃脱

system("grep -v 'utc\\s*\$' $old_file > $new_file");

这适用于我的系统。

第一:简单的Perl

perl -e 'opendir DH,"/doc";foreach my $date (readdir DH) {
   if (-f "/doc/".$date."/before") { open RH,"</doc/".$date."/before";
     open WH,">/doc/".$date."/after";while(<RH>){print WH $_ unless /utc$/;};};
   close RH;close WH;};closedir DH;'

或作为脚本:

#!/usr/bin/perl -w

my $docPath="/doc";
opendir DH,$docPath;
foreach my $date (readdir DH) {
    if (-f $docPath."/".$date."/before") {
        open RH,"<".$docPath."/".$date."/before";
        open WH,">".$docPath."/".$date."/after";
        while(<RH>){
            print WH $_ unless /utc$/;
        };
    };
    close RH;
    close WH;
};
closedir DH;

或使用Path::Tiny

#!/usr/bin/perl -w

use Path::Tiny;

my $docPath=path("/doc");

foreach my $date ($docPath->children) {
    $date->child("after")->spew(
    grep {!/utc$/} $date->child("before")->lines );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM