簡體   English   中英

我正在嘗試使用Perl修改文本文件中的某些內容

[英]I am trying to modify some content in text file using perl

我試圖在Perl腳本中使用正則表達式修改文本文件中的某些內容,但未修改任何內容,但是當我在文本板中使用相同的正則表達式時,它會修改

輸入

    ab 3fdfs2sd 6 Feb 2015.doc Creatings som junk text: ccpsd(1).xml.
    sdfdgd .df . fds  18 Mar 2015.doc  Creatings som junk text: ccpsd(2).xml.

要求的輸出:

    ccpsd(1).xml-ab 3fdfs2sd 6 Feb 2015.xml
    ccpsd(2).xml-sdfdgd .df . fds  18 Mar 2015.xml

    use strict;
    open(FILE, "<G:/in.txt") || die "File not found";
     my @lines = <FILE>;  
     close(FILE);

    my @newlines;
    foreach(@lines) {

       $_ =~ s/(^.+?)\.doc\s*.+?[\:]\s*(CC.+?xml)\./\2-\1.xml/igs;

          push(@newlines,$_);
    }

    open(FILE, ">/out.txt") || die "File not found";
    print FILE @newlines;
    close(FILE);

您應該使用雙>>並指定文件名:

my $outfile = 'out.txt';
open (FILE, ">> $outfile") || die "File not found";

如本示例程序中所述 ,正則表達式很好。

在我看來,您錯過了驅動器的輸出文件。
我會做:

#!/usr/bin/perl
use strict;
use warnings;

my $in_file  = 'G:/in.txt';
my $out_file = 'G:/out.txt';

open my $in, '<', $in_file or die "Unable to open '$in_file': $!";
open my $out, '>', $out_file or die "Unable to open '$out_file': $!";
while(<$in>) {
    chomp;
    s/^(.+?)\.doc\s*.+?:\s*(CC.+?xml)\./$2-$1.xml/i;
    print $out $_,"\n";
}

只需使用Perl一線

perl -pe's/(^.+?)\.doc\s*.+?[\:]\s*(CC.+?xml)\./\2-\1.xml/ig'

順便說一句,您閱讀過perldoc perlre嗎?確定要了解嗎? 因為您在代碼中是通過行和s修飾符讀取輸入文件的,所以沒有任何意義。 如果您真的想對多行模式應用正則表達式,則應該使用。

perl -0777 -pe's/(^.+?)\.doc\s*.+?[\:]\s*(CC.+?xml)\./\2-\1.xml/igs'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM