且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取第 n 行 STDOUT 的命令

更新时间:2023-12-01 09:48:10

使用 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'