如何使用perl从第n行写入文件 [英] How to write from n-th row to a file using perl

查看:60
本文介绍了如何使用perl从第n行写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件中有一个源文本,我正在寻找一个代码,该代码将从该文件中取出第二行(或第 n 行,一般来说)并打印到一个单独的文件中.

I have a source text in a file and looking for a code that would take the second (or n-th - in general) row from this file and print to a seperate file.

知道怎么做吗?

推荐答案

您可以使用 触发器运算符和特殊变量$.(由 .. 内部使用),包含当前行号:

You can do this natively in Perl with the flip-flop operator and the special variable $. (used internally by ..), which contains the current line number:

# prints lines 3 to 8 inclusive from stdin:
while (<>)
{
    print if 3 .. 8;
}

或者从命令行:

perl -wne'print if 3 .. 8' < filename.txt >> output.txt

你也可以在没有 Perl 的情况下使用:head -n3 filename.txt |尾-n1>>output.txt

You can also do this without Perl with: head -n3 filename.txt | tail -n1 >> output.txt

这篇关于如何使用perl从第n行写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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