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
命令提供的输出的第一行。
使用 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)
你会做
sed '2q;d' <(tac infile)
Run Code Online (Sandbox Code Playgroud)
tac
infile
以相反的顺序打印文件,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)