如何从 Unix 中的文件打印特定行? [英] How can I print specific lines from a file in Unix?

查看:49
本文介绍了如何从 Unix 中的文件打印特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Unix 中的文本文件中打印某些行.要打印的行号列在另一个文本文件中(每行一个).

I want to print certain lines from a text file in Unix. The line numbers to be printed are listed in another text file (one on each line).

是否有使用 Perl 或 shell 脚本快速执行此操作的方法?

Is there a quick way to do this with Perl or a shell script?

推荐答案

假设要打印的行号已排序.

Assuming the line numbers to be printed are sorted.

open my $fh, '<', 'line_numbers' or die $!;
my @ln = <$fh>;
open my $tx, '<', 'text_file' or die $!;
foreach my $ln (@ln) {
  my $line;
  do {
    $line = <$tx>;
  } until $. == $ln and defined $line;
  print $line if defined $line;
}

这篇关于如何从 Unix 中的文件打印特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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