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

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

问题描述

是否有任何bash命令可以让您获得STDOUT的第n行?

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,返回特定行),但是我想知道是否有一些 standard 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,仅用于变化:

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'

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

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