2016-04-22 80 views
-1

分割每行字符串我有一個包含這樣的字符串的文件:我怎麼能對文件

- ' *[0-9]-? [^a-c]@[*-^a-c]' '' < temp-test/758.inp.325.1 
- ' *[0-9]-? [^a-c]@[*-^a-c]' '' < temp-test/759.inp.325.3 
- ' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' 'NEW' < temp-test/1133.inp.487.1`enter code here` 
- ' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' 'NEW' < temp-test/1134.inp.487.2 
- '"@@' 'm' < input/ruin.1890 

我想分割每行此字符串爲2部分,我希望這樣的結果:

- line 1: array[0]=' *[0-9]-? [^a-c]@[*-^a-c]'; array [1]='' < temp-test/758.inp.325.1 
- line 2: array[0]=' *[0-9]-? [^a-c]@[*-^a-c]'; array [1]='' < temp-test/759.inp.325.3 
- line 3: array[0]=' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]'; array[1]='NEW' < temp-test/1133.inp.487.1 
- line 4: array[0]=' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]'; array[1]='NEW' < temp-test/1134.inp.487.2 
- line 5: array[0]='"@@'; array[1]='m' < input/ruin.1890 

,我已經嘗試的代碼是這樣的:

#!/usr/bin/perl 

# location of universe file 
$tc = "/root/Desktop/SIEMENS/replace/testplans.alt/universe"; 

# open file universe; 
open(F, "<$tc"); 
@test_case = <F>; 

while ($i < 5) { 

    $test_case[$i] =~ s/ //; 
    @isi = split(/ /, $test_case[$i]); 

    if ($#isi == 2) { 
     print "Input1:" . $isi[0] . "\n"; 
     print "Input2:" . $isi[1] . "\n"; 
     print "Input3:" . $isi[2] . "\n"; 
    } 

    $i++; 
} 

我很困惑,因爲我不能縫該字符串以「」(SPAC e),因爲每一行有不同的訂單空間,我不能成爲2部分。 謝謝。

+0

不要使用拆分對於這一點,使用正則表達式。 http://perldoc.perl.org/perlre.html – xxfelixxx

+0

https://regex101.com/ – xxfelixxx

+0

請用清晰的例子編輯您的文章,並清楚輸出您確切需要的內容。 – mkHun

回答

0
use strict; 
use warnings; 

# this stuff just gives me your data for testing 

my $data =<<EOF; 
' [0-9]-? [^a-c]\@[-^a-c]' '' < temp-test/758.inp.325.1 
' [0-9]-? [^a-c]\@[-^a-c]' '' < temp-test/759.inp.325.3 
' *[0-9]\@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' 'NEW' < temp-test/1133.inp.487.1 
' *[0-9]\@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' 'NEW' < temp-test/1134.inp.487.2 
'"\@\@' 'm' < input/ruin.1890 
EOF 

for my $line (split(/\n/,$data)) 
{ 

    # this re splits your strings according 
    # to what I perceive to be your requirements 

    if ($line =~ /^(.*)('.*?' <.*)$/) 
    { 
     print("array[0]=$1; array[1]=$2;\n") 
    } 
} 


1; 

輸出:

array[0]=' [0-9]-? [^a-c]@[-^a-c]' ; array[1]='' < temp-test/758.inp.325.1; 
array[0]=' [0-9]-? [^a-c]@[-^a-c]' ; array[1]='' < temp-test/759.inp.325.3; 
array[0]=' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' ; array[1]='NEW' < temp-test/1133.inp.487.1 
array[0]=' *[0-9]@[[9-B]??[0-9]-[^-[^0-9]-[a-c][^a-c]' ; array[1]='NEW' < temp-test/1134.inp.487.2; 
array[0]='"@@' ; array[1]='m' < input/ruin.1890; 

應用到你的代碼,它可能是這個樣子:

while ($i<5) 
{ 

    $test_case[$i] =~ /^(.*)('.*?' <.*)$/; 
    @isi = ($1,$2); 

    print "Input1:".$isi[0]."\n"; 
    print "Input2:".$isi[1]."\n"; 

    $i++; 
}