首页 > 解决方案 > 在文件中剪切并粘贴特定字符串

问题描述

在一个文件中,我需要剪切文本(以 的形式\qr{....text})并放置在两个回车之后。

输入文件文本将是:

\section{bla bla ...\qr{text} bla bla..}

Some paragraph text......

所需输出:

\section{bla bla bla bla}

\qr{text}......
Some paragraph text 

我的尝试:

use strict;
use warnings;

my $InputXmlFile = $ARGV[0];
my $OutputXmlFile = $InputXmlFile;
my $OutProcesText = "";
$OutputXmlFile =~ s#\.tex$#\.tex#gsi;
my $workingpath = $1 if $InputXmlFile =~ m/(.*)\\(.+)\.tex/i;
my $filename = $2 if $InputXmlFile =~ m/(.*)\\(.+)\.tex/i;

open (INTXT, "$InputXmlFile");
my $inText = join("",<INTXT>);
close (INTXT);

while($inText =~ m#\\section\{(.*?)\}\n\n#gi) {
    my $qrtext = $1;
    if ($qrtext =~s/\\qr\{(.*?)\}//gi) {
        my $qrFindText = $1;
        $qrtext =~ s/\x0D\x0D/\x0D\x0D$qrFindText/g; 
        print $qrFindText;
    }
    open (FIH,'>',$OutputXmlFile);
    print FIH $inText;
    close(FIH);
}

标签: perl

解决方案


请试试这个:

use strict;
use warnings;

my $brc = qw/((?:[^{}]*(?:{(?:[^{}]*(?:{(?:[^{}]*(?:{[^{}]*})*[^{}]*)*})*[^{}]*)*})*[^{}]*)*)/;
my $InputXmlFile = $ARGV[0]; (my $OutputXmlFile = $InputXmlFile)=~s/\.tex$/\.newtex/i;

open(INTXT, $InputXmlFile) || die "Couldn't able to read: $!\n";
my $inText = join("",<INTXT>);
close(INTXT);

my ($beh,$match,$byn) = "";
while($inText=~m/\\section\{$brc\}/gs)
{
    $beh = $beh.$`; $match = $&; $byn = $'; my $qrt = $1;
    if($qrt=~m/\\qr{$brc}/i) { my $qrtex = $&; $match=~s/\\qr\{$brc\}//; $match=~s/$/\n\n$qrtex/; }
    $beh = $beh.$match; $inText = $byn;
}
if(length $beh) {  $inText = $beh.$byn;  }

open(FIH,'>',$OutputXmlFile);
print FIH $inText;
close(FIH);

推荐阅读