如何在 perl 中删除文件的最后 10 行 [英] How can I delete the last 10 lines of a file in perl

查看:54
本文介绍了如何在 perl 中删除文件的最后 10 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将总行数作为用户输入,然后从文件中删除这些行数.

I am taking a total number of line as a user input and then I am deleting those numbers of l ine from the file.

我看到了这个 learn.perl.org/faq/perlfaq5.html#How-do-I-count-the-number-of-lines-in-a-file- 然后我厌倦了下面的简单逻辑.

I saw this learn.perl.org/faq/perlfaq5.html#How-do-I-count-the-number-of-lines-in-a-file- and then I tired the below simple logic.

逻辑:

  1. 获取总行数
  2. 用用户输入的数字减去它
  3. 打印线条

这是我的代码:

#!/usr/bin/perl -w
use strict;

open IN, "<", "Delete_line.txt"
    or die " Can not open the file $!";
open OUT, ">", "Update_delete_line.txt" 
    or die "Can not write in the file $!";

my ($total_line, $line, $number, $printed_line);

print"Enter the number of line to be delete\n";
$number = <STDIN>;

while ($line = <IN>) {

    $total_line = $.;  # Total number of line in the file
}

$printed_line = $total_line - $number;

while ($line = <IN>) {

    print OUT $line unless $.== $printed_line;      
}

好吧,我既没有收到任何代码错误,也没有任何输出?为什么我只是不知道.

Well, neither i am getting any error in code nor any out put ? why I just don't know.

谁能给我一些建议.

推荐答案

对大文件有效的 Perl 解决方案需要使用 File::ReadBackwards

A Perl solution that's efficient for large files requires the use of File::ReadBackwards

use File::ReadBackwards qw( );

my $num_lines = 10;
my $qfn = 'file.txt';

my $pos = do {
   my $fh = File::ReadBackwards->new($qfn)
      or die $!;
   $fh->readline() for 1..$num_lines;
   $fh->tell()
};

truncate($qfn, $pos)
   or die $!;

  • 这不会读取整个文件两次(与 OP 的方法不同).
  • 这不会读取整个文件(与 Tie::File 解决方案不同).立>
  • 这不会将整个文件读入内存.
  • 这篇关于如何在 perl 中删除文件的最后 10 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆