仅显示文本的倒数第二行(倒数第二行)

Ele*_*na 7 sed awk tail text-processing ed

我有一个未知的行数的一首诗,我想只显示倒数第一位。我应该使用什么命令?

Isk*_*tvo 19

有很多方法可以做到这一点,但是这是最快的国家之一,我发现 - 而且是在我看来,最干净的。

假设这首诗写在一个名为 的文件中poem,您可以使用:

tail -n 2 poem | head -n 1
Run Code Online (Sandbox Code Playgroud)

tail -n 2 poem将写入文件的最后 2 行poem

head -n 1将写入上一个tail命令提供的输出的第一行。


Jef*_*ler 7

使用 ed,伙计!

ed -s poems <<< $'$-1\n'
Run Code Online (Sandbox Code Playgroud)

这告诉 ed 以poems脚本模式 ( -s)打开文件(这样它不会打印额外的消息),然后在此处的字符串中发送一个寻址命令,表示“转到文件的最后一行 ( $),减去 1 ",打印该行。

给定一个输入诗文件

A is for awk, which runs like a snail, and
B is for biff, which reads all your mail.

C is for cc, as hackers recall, while
D is for dd, the command that does all.

E is for emacs, which rebinds your keys, and
F is for fsck, which rebuilds your trees.

G is for grep, a clever detective, while
H is for halt, which may seem defective.

I is for indent, which rarely amuses, and
J is for join, which nobody uses.

K is for kill, which makes you the boss, while
L is for lex, which is missing from DOS.

M is for more, from which Less was begot, and
N is for nice, which it really is not.

O is for od, which prints out things nice, while
P is for passwd, which reads in strings twice.

Q is for quota, a Berkeley-type fable, and
R is for ranlib, for sorting ar sic table.

S is for spell, which attempts to belittle, while
T is for true, which does very little.

U is for uniq, which is used after Sort, and
V is for vi, which is hard to abort.

W is for whoami, which tells you your name, while
X is, well, X, of dubious fame.

Y is for yes, which makes an impression, and
Z is for zcat, which handles compression.
Run Code Online (Sandbox Code Playgroud)

...结果输出是:

Y is for yes, which makes an impression, and
Run Code Online (Sandbox Code Playgroud)


αғs*_*нιη 5

你会做

sed '2q;d' <(tac infile)
Run Code Online (Sandbox Code Playgroud)

tacinfile以相反的顺序打印文件,cat并将其作为输入传递给sed,这将删除除第二行之外的每一行(这里只有第一行),然后立即退出。

或者:

tail -n2 infile | sed '2d'
Run Code Online (Sandbox Code Playgroud)

或者sed只有

sed 'x;$!d' <infile
Run Code Online (Sandbox Code Playgroud)

sed是读一行在时间和保持空间的x,我们保存当前行处理,并将其打印!d(不要删除)一旦sed的读取所有行(或者它在最后一行),自sed中只能有一个保持-space,所以当它是最后一行时,保持空间包含倒数第二行;这与:

sed -n 'x;$p' <infile
Run Code Online (Sandbox Code Playgroud)


小智 3

假设你的诗在poem文本文档中:

< poem tail -n 2 | head -n 1
Run Code Online (Sandbox Code Playgroud)

  • @BlackJack,有很多优点。第一个是它允许您在管道的开头更改文件名(IMO 非常常见且不神秘,并且可以更好地显示数据流),如果文件不能被运行,它可以避免运行“tail”打开并使用任意文件名(`tail -n 2 "$file"` 对于以 `-` 开头的 `$file` 会失败。`tail -n 2 -- "$file"` 对于以 `-` 开头的 `$file` 仍然会失败。文件名为“-”) (6认同)
  • 我第一次看到这种情况,所以我认为这并不常见。☺ 在我看来,“tail -n 2 &lt;诗”更好地展示了流程,因为“&lt;”象征着一个箭头,描绘了从“诗”到“尾”的流程。 (2认同)