You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Perl中从文件顶部截断以保留指定大小的文件

Perl实现文件超过指定大小后删除顶部内容

场景说明

针对你持续追加数据的file.txt,以下提供两种实用的Perl实现方案,满足文件体积超过800MB时删除顶部内容的需求。

方案一:超过大小直接清空文件

适合不需要保留任何历史数据,仅需后续追加新内容的场景:

#!/usr/bin/perl
use strict;
use warnings;

my $target_file = 'file.txt';
# 换算800MB为字节数
my $max_allowed_size = 800 * 1024 * 1024;

if (-e $target_file) {
    my $current_size = -s $target_file;
    if ($current_size > $max_allowed_size) {
        # 以写入模式打开文件,自动清空所有内容
        open my $fh, '>', $target_file or die "无法打开文件写入: $!";
        close $fh;
        print "文件已清空,原大小超过阈值: $current_size 字节\n";
    } else {
        print "文件大小正常: $current_size 字节\n";
    }
} else {
    print "目标文件 $target_file 不存在\n";
}

方案二:保留尾部最新内容,删除顶部旧数据

更实用的滚动日志场景:当文件超限时,保留指定大小的最新内容(示例为最后700MB),删除旧的头部数据:

#!/usr/bin/perl
use strict;
use warnings;
use Fcntl qw(:flock);

my $target_file = 'file.txt';
my $max_allowed_size = 800 * 1024 * 1024; # 800MB
my $retain_size = 700 * 1024 * 1024;     # 保留最后700MB

if (-e $target_file) {
    my $current_size = -s $target_file;
    if ($current_size > $max_allowed_size) {
        # 打开文件并加共享锁,避免并发写入冲突
        open my $fh_in, '<', $target_file or die "无法打开文件读取: $!";
        flock $fh_in, LOCK_SH or die "无法锁定文件读取: $!";
        
        # 定位到需要保留的内容起始位置
        seek $fh_in, $current_size - $retain_size, 0;
        my @latest_content = <$fh_in>;
        close $fh_in;
        
        # 打开文件并加排他锁,写入保留的内容
        open my $fh_out, '>', $target_file or die "无法打开文件写入: $!";
        flock $fh_out, LOCK_EX or die "无法锁定文件写入: $!";
        print $fh_out @latest_content;
        close $fh_out;
        
        my $new_size = -s $target_file;
        print "文件已修剪,保留最后 $retain_size 字节,新大小: $new_size 字节\n";
    } else {
        print "文件大小正常: $current_size 字节\n";
    }
} else {
    print "目标文件 $target_file 不存在\n";
}

定时执行配置

由于文件每分钟都会追加数据,需要定时运行脚本检查处理:

  • Linux/Unix:编辑crontab(执行crontab -e),添加以下行实现每分钟执行:
* * * * * /usr/bin/perl /path/to/your/script.pl
  • Windows:通过「任务计划程序」创建定时任务,设置每分钟执行该Perl脚本。

注意事项

  • 加入flock文件锁是为了避免脚本与其他写入进程的并发冲突,防止数据损坏或丢失。
  • 可根据实际需求调整$retain_size的值,比如改为保留最后500MB。

内容的提问来源于stack exchange,提问作者PPP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 02:05:56