perl 文本文件按5000行拆分成小文本文件
时间: 2023-10-03 18:06:51 浏览: 60
可以使用 Perl 的文件操作函数来实现将大文本文件按照指定行数分割成小文本文件的功能。
以下是一个示例代码,可以将大文本文件 `input.txt` 按照每个文件 5000 行的大小拆分成若干个小文本文件,并以 `output_1.txt`、 `output_2.txt`、 `output_3.txt` ... 的方式命名保存。
```perl
#!/usr/bin/perl
use strict;
use warnings;
# 每个输出文件的行数
my $lines_per_file = 5000;
# 输入文件名
my $input_file = "input.txt";
# 输出文件名前缀
my $output_file_prefix = "output_";
# 初始化计数器和输出文件名
my $line_count = 0;
my $file_count = 1;
my $output_file = "$output_file_prefix$file_count.txt";
# 打开输入和输出文件
open(INPUT, "<", $input_file) or die "Cannot open $input_file for reading: $!";
open(OUTPUT, ">", $output_file) or die "Cannot open $output_file for writing: $!";
# 逐行读取输入文件并写入输出文件
while (my $line = <INPUT>) {
# 计数器加1
$line_count++;
# 如果计数器达到了指定行数,关闭当前输出文件并打开新的输出文件
if ($line_count > $lines_per_file) {
close(OUTPUT);
$file_count++;
$output_file = "$output_file_prefix$file_count.txt";
open(OUTPUT, ">", $output_file) or die "Cannot open $output_file for writing: $!";
$line_count = 0;
}
# 将当前行写入输出文件
print OUTPUT $line;
}
# 关闭输入和输出文件
close(INPUT);
close(OUTPUT);
```
这个代码中,我们首先指定每个输出文件的行数 `$lines_per_file` 和输入文件名 `$input_file`,然后初始化计数器和输出文件名,打开输入和输出文件。接着,我们逐行读取输入文件,并将当前行写入输出文件。每当计数器达到了指定行数时,关闭当前输出文件并打开新的输出文件,重置计数器和输出文件名。
你可以根据实际需求修改代码中的参数,比如输出文件名前缀、每个输出文件的行数等等。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)