2014-11-11 3 views
1

내가 파일에서 문자열을 검색하여 다른 문자열로 그것을 대체하려고에서 서로 파일에 문자열을 대체, 내가 가진 내가 SerialPort=500에 라인 SerialPort=100을 대체 할찾아 펄

#comments abc 
#comments xyz 
SerialPort=100 #comment 
Baudrate=9600 
Parity=2 
Databits=8 
Stopbits=1 

같은 파일 내용 파일의 다른 내용을 변경하지 않고 SerialPort = 100 옆의 주석을 변경해서는 안되지만 스크립트를 작성했지만 실행 후 모든 주석 행이 삭제됩니다. 이 위 요구 사항에 대한 정규 표현식 도와주세요, 여기

my $old_file = "/home/file"; 
my $new_file = "/home/temp"; 
open (fd_old, "<", $old_file) || die "cant open file"; 
open (fd_new, ">", $new_file) || die "cant open file"; 
while (my $line = <fd_old>) { 
    if ($line =~ /SerialPort=(\S+)/) { 
     $line =~ s/SerialPort=(\S+)/SerialPort=$in{'SerialPort'}/; 
     print fd_new $line; 
    } 
    else { 
     print fd_new $line; 
    } 
} 
close (fd_new); 
close (fd_old); 
rename ($new_file, $old_file) || die "can't rename file"; 
+0

은 주석 삭제 라인 (라인 1인가 그것은이 같은 상황에서 탁월 2 파일에)? – Jens

+0

예, 모든 댓글 만 삭제됩니다. – Maruti

+2

그것은 나를 위해 작동합니다. 전화 한 정확한 스크립트를 보여 봤어? '/^#/and next' 또는 이와 비슷한 줄이 없습니까? – choroba

답변

1
use strict; 
my %in; 
$in{SerialPort} = 500; 
my $old_file = "file"; 
my $new_file = "temp"; 
open my $fd_old, "<", $old_file or die "can't open old file"; 
open my $fd_new, ">", $new_file or die "can't open new file"; 

while (<$fd_old>) { 
    s/(?<=SerialPort=)\d+/$in{'SerialPort'}/; 
    print $fd_new $_; 
} 

close ($fd_new); 
close ($fd_old); 
rename $new_file, $old_file or die "can't rename file"; 
1

대신 나오지 사용을 고려 내 코드입니다. 당신이 편집해야 할 많은 파일이있는 경우

sed -i 's/SerialPort=100/SerialPort=500/' /path/to/file 

, 쌍 찾아 xargs를 함께 나오지 :

find /path/to/directory -type f -name '*.ini' -print0 | xargs -0n16 sed -i 's/SerialPort=100/SerialPort=500/' 
1
perl -pe 's/findallofthese/makethemthis/g' input.txt > output.txt