使用換行做爲分界
忽略註釋行#
分割存入新指定的文件中code
test.lst
wwdg/prescaler syscfg/test1 syscfg/test2 uart/uart7/uart7_dma1 uart/uart7/uart7_dma2
genlst.pl
#!/usr/bin/perl use warnings; ########################################### #cut up file # #cut_flie.pl test.lst ########################################### my $find_ip =0; my $find_begin = 0; my $line_index = 0; my $lstname = "error"; my $past_line = "error"; my $infile= $ARGV[0]; open(INFILE, " $infile") || die ("Could not open file $infile ! \n"); if(-z $infile){ print "\nFile is blank!\n"; exit; } #覆蓋lst中的文件,需手動刪除已經存在的文件 my $dir = "lst"; #建立存放目錄 if(-e $dir){ } else{ mkdir $dir; } #刪除lst中的文件 #my $dir = "lst"; #建立存放目錄 #if(-e $dir){ # unlink glob "$dir/* $dir/.*" #} #else{ # mkdir $dir; #} # get file lines amount my @fileline = <INFILE>; #獲得文件的行數 my $line_num = @fileline; close INFILE; unlink "temp.lst"; open(TEMPA, ">> temp.lst") || die ("Could not open file temp.lst! \n"); open(INFILE, " $infile") || die ("Could not open file $infile ! \n"); while ($line = <INFILE>){ $line_index ++; chomp($line); if($line =~ /^#/) { #find "#" at the beginning, don't care next; } if($line =~ /^(\w+)[\s\$\W]*/){ #匹配捕獲字符串,非空行 if($past_line =~ /^$/){ #上一行爲空最爲分界 print TEMPA "\n\n"; my $full_lstname = $lstname."_lst"; print "$dir\/$full_lstname\n"; rename "temp.lst", "$full_lstname"; close TEMPA; #完成一個文件的分割 system"mv $full_lstname lst"; print "\n\n"; unlink "temp.lst"; open(TEMPA, ">> temp.lst") || die ("Could not open file temp.lst! \n"); #繼續進行下一個文件處理 } $line =~ /^(\w+)[\s\$\W]*/ ; #正則處理,獲得文件名 print TEMPA "$line \n"; print "$line \n"; $lstname = $1; } if($line_index == $line_num){ #單獨處理最後行狀況 print TEMPA "\n\n"; #print "\n\n"; my $full_lstname = $lstname."_lst"; print "$dir\/$full_lstname\n"; rename "temp.lst", "$full_lstname"; close TEMPA; system"cp $full_lstname lst"; unlink "$full_lstname"; } if($line =~ /^\s*$/){ if($line_index == 1){ next; } if($past_line =~ /^$/){ next; } } $past_line = $line; #保存上一行狀況 } close INFILE; close TEMPA; unlink "temp.lst"; unlink "lst/error_lst";