Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何从输入文件中提取部分文本并写入另一个文件?_Regex_Perl_Text_Extract - Fatal编程技术网

Regex 如何从输入文件中提取部分文本并写入另一个文件?

Regex 如何从输入文件中提取部分文本并写入另一个文件?,regex,perl,text,extract,Regex,Perl,Text,Extract,这是我的密码。我希望提取部分文本并写入另一个文件。代码循环不会在我选择的文本范围内停止。它一直读到单词的最后一行。请告诉我。谢谢例如,我需要将$NAME:sandy提取到$$,然后加入$NAME:patrick中的内容,该内容从G1开始到$$SRU 正文: 代码: use strict; use warnings; open my $F1, '<', 'testing.txt' or die "failed $!"; open my $F2, '>', 'out.txt' or d

这是我的密码。我希望提取部分文本并写入另一个文件。代码循环不会在我选择的文本范围内停止。它一直读到单词的最后一行。请告诉我。谢谢例如,我需要将$NAME:sandy提取到$$,然后加入$NAME:patrick中的内容,该内容从G1开始到$$SRU

正文:

代码:

use strict;
use warnings;

open my $F1, '<', 'testing.txt' or die "failed $!";
open my $F2, '>', 'out.txt' or die "failed $!";

while (<$F1>) {
if (/^\$ NAME : sandy/../\$.TO/) {
print $F2 $_;
}
if (/^\$ NAME : patrick/../\$.EON/) {
if(/^G1/../\$SRU){
 s/G1/G1.G1o.n/g;
print $F2 $_;}
}

 }
close $F1;
close $F2;
使用严格;
使用警告;
打开我的$F1、、'out.txt'或死“failed$!”;
而(){
如果(/^\$NAME:sandy/./\$.TO/){
打印$F2$;
}
如果(/^\$NAME:patrick/./\$.EON/){
如果(/^G1/./\$SRU){
s/G1/G1.G1o.n/g;
打印$F2$\}
}
}
收盘价$F1;
收盘价$F2;

首先,正则表达式中的
前面没有足够的空间,您会使代码复杂化

use warnings;
use strict;

open my $fh, '<', 'in' || die "Can not open file:$!\n";;

while (<$fh>){
        print if /^\$ NAME : corry/../\$\$\.EON/;
}
close $fh;
然后可以打印到此文件,就像打印到屏幕一样:

print $fh2 'some text here'; #print to file handler $fh2 string 'some text here'

您需要提取哪段文本?从这里开始->$NAME:corry$$.Inc s d$$.Oc s$$到G1 ty n1 EE EE M T1 T2$$SRU G2 n1 y OOO M T3 T4$$SRU$$。谢谢!它很好用。你能告诉我一些关于如何将选择文本范围内的G1替换为G1.G1o.n并将新文本写入另一个文件的想法吗?实际上,这个文本是整个文本中的一些简单部分。G1.G1o.n表示层次结构组织。我的perl技能还不是标准的,所以我想用比较旧的方法将G1替换为G1.G1o。最终的层次结构部分有很多小部分。科里和帕特里克是层次结构的一部分。整体层次结构在部门经理之下,我没有在上面发布。可能是因为我的英语不好或是因为星期一,但我真的不明白你想做什么,对不起:D如果你想将以G1开头的行写入另一个文件,你可以这样做
while(){if(//../){print$fh2$\if/^G1/;}
噢,它的意思是
while(){if/^\$NAME:corry/./\$\$\$\.EON/;{print$fh2$\uif/^G1/;}}
?抱歉,是否需要添加一些内容来创建输出文件?
open my $fh2, '>>', 'my_out_file.txt'; #open file handler $fh2 associated with file named my_out_file.txt
print $fh2 'some text here'; #print to file handler $fh2 string 'some text here'