awk

awk

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

答案1

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

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

tail -n 2 poem | head -n 1

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

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

答案2

使用ed,伙计!

ed -s poems <<< $'$-1\n'

poems这告诉 ed以脚本模式 ( )打开文件-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.

...结果输出是:

Y is for yes, which makes an impression, and

答案3

你会做

sed '2q;d' <(tac infile)

tacinfile我们将以相反的顺序打印文件cat,与将其作为输入传递给一样sed,这将删除除第二行之外的每一行(此处仅第一行),然后立即退出。

或者:

tail -n2 infile | sed '2d'

或者sed仅与

sed 'x;$!d' <infile

sed一次读取一行,并使用保留空间保存x当前行处理并将其打印!d一次(不要删除)sed读取所有行(或者在最后一行),因为sed只能有一个保留空间,因此当它是最后一行时,保留空间包含倒数第二行;这与:

sed -n 'x;$p' <infile

答案4

awk

这适用于 GNU awk (Linux) 和 BSD awk (Mac)。

您可能想忽略空行。在这种情况下,您可以使用awk 'NF' file.txt,然后通过本页描述的其他方法之一通过管道输出。

您还可以通过 awk 一次完成所有操作:

awk 'NF { a=b ; b=$0 } END { print a }' file.txt
  • NF
    仅处理包含数据的行。 NF代表行中的字段数;大于 0 的值被视为“true”。
    • { a=b ; b=$0 }
      将当前非空行存储为b,将上一个非空行存储为a
  • END { print a }
    检查整个文件后,打印a(倒数第二个非空行)的最终值。

如果您不想省略空行,只需删除NF

awk '{ a=b ; b=$0 } END { print a }' file.txt

相关内容