获取第 n 行 STDOUT 的命令 [英] Command to get nth line of STDOUT

查看:20
本文介绍了获取第 n 行 STDOUT 的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么bash命令可以让你得到第n行STDOUT吗?

Is there any bash command that will let you get the nth line of STDOUT?

也就是说,会拿这个的东西

That is to say, something that would take this

$ ls -l
-rw-r--r--@ 1 root  wheel my.txt
-rw-r--r--@ 1 root  wheel files.txt
-rw-r--r--@ 1 root  wheel here.txt

然后做类似的事情

$ ls -l | magic-command 2
-rw-r--r--@ 1 root  wheel files.txt

我意识到在编写打算重用的脚本时这将是不好的做法,但是在日常使用 shell 时,能够以这种方式过滤我的 STDOUT 对我来说很有用.

I realize this would be bad practice when writing scripts meant to be reused, BUT when working with the shell day to day it'd be useful to me to be able to filter my STDOUT in such a way.

我也意识到这将是半简单的写入命令(缓冲 STDOUT,返回特定行),但我想知道是否有一些 标准 shell 命令可以执行此操作无需我将脚本放置到位.

I also realize this would be semi-trivial command to write (buffer STDOUT, return a specific line), but I want to know if there's some standard shell command to do this that would be available without me dropping a script into place.

推荐答案

使用 sed,只是为了变化:

Using sed, just for variety:

ls -l | sed -n 2p

使用这种看起来更有效的替代方法,因为它会在打印所需的行时停止读取输入,但可能会在送入过程中生成 SIGPIPE,进而可能会生成不需要的错误消息:

Using this alternative, which looks more efficient since it stops reading the input when the required line is printed, may generate a SIGPIPE in the feeding process, which may in turn generate an unwanted error message:

ls -l | sed -n -e '2{p;q}'

我经常看到这种情况,我通常使用第一个(无论如何,它更容易输入),尽管 ls 不是一个在获得 SIGPIPE 时会抱怨的命令.

I've seen that often enough that I usually use the first (which is easier to type, anyway), though ls is not a command that complains when it gets SIGPIPE.

对于一系列行:

ls -l | sed -n 2,4p

对于多个行范围:

ls -l | sed -n -e 2,4p -e 20,30p
ls -l | sed -n -e '2,4p;20,30p'

这篇关于获取第 n 行 STDOUT 的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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