gpt4 book ai didi

Perl:如何拆分文件?

转载 作者:行者123 更新时间:2023-12-01 23:18:35 25 4
gpt4 key购买 nike

我需要将一个文件拆分成不同的文件。

示例(原始文件):

*****3123123*****RAW
text1
text2
*****2312354***RAW
text3

期望的输出:

[文件1.txt]

*****3123123*****RAW    
text1
text2

[文件2.txt]

*****312312354***RAW
text3

我尝试使用拆分,但我总是将一些额外的白色字符放入数组中

open FILE, "<file";
@file= <FILE>;
close FILE;
@lines = split (/(RAW\n)/, "@file");
foreach $value (@lines) {
if ($value =~ /[a-z]|[A-Z]|[1-9]/) {
print ("$value\n");
}
}

输出:

*****3123123*****RAW

text1
text2

*****312312354***RAW

text3

编辑:如果我使用 print ("$value") 而不是 print ("$value\n") 这就是输出(注意值之前的 1 个额外空格:

*****3123123*****RAW
text1
text2

*****12354***RAW
text3

最佳答案

此程序从 RAW 行中提取十进制数,并使用它来命名输出文件。它期望输入文件名作为命令行上的参数。

use strict;
use warnings;

@ARGV or die "Input file required as command-line parameter\n";

my $out;

while (<>) {
if ( /(\d+)\*+RAW$/ ) {
open $out, '>', "$1.out" or die $!;
select $out;
}
print $_ if $out;
}

关于Perl:如何拆分文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10948854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com