壳牌/ bash命令来获得STDOUT的第n行 [英] Shell/Bash Command to get nth line of STDOUT

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

问题描述

有没有bash命令,可以让你得到STDOUT的第n行?

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

这就是说,一些想借此

$ 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

我知道这是不好的做法,当编写脚本可以重复使用,但与外壳的日常工作​​时,它会是有用的我能够过滤我的标准输出以这样的方式。

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 ,只是品种:

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'

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

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