3.3《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——less即more

Unix提供了两个工具查看不止文件的头部和尾部。这个功能程序叫作more,但有种更强大的变异体叫作less(起初我认为这是玩笑)。less这个程序是交互性地,因此很难在输出时捕获,可是仍然为你们提供了粗略地样本以下:html

$ less sonnets.txt
Shake-speare's Sonnets

I

From fairest creatures we desire increase,
That thereby beauty's Rose might never die,    
But as the riper should by time decease,
His tender heir might bear his memory:
But thou contracted to thine own bright eyes,
Feed'st thy light's flame with self-substantial fuel,
Making a famine where abundance lies,
Thy self thy foe, to thy sweet self too cruel:
Thou that art now the world's fresh ornament,
And only herald to the gaudy spring,
Within thine own bud buriest thy content,
And tender churl mak'st waste in niggarding:
Pity the world, or else this glutton be,
To eat the world's due, by the grave and thee.

II

When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
sonnets.txt

less程序地关键点在于它提供了几种有用的方法让你到文件的指定位置,例如使用箭头向上或向下移动整行内容,按空格键移到页面底部,按^F向前移一页(例如,)或者 ^B向后移一页。退出less, 输入q(‘quit’简写)。spring

插图18: 莎士比亚时期著名的玫瑰

或许,less最强大的能力是斜杠键/了,它能让你从文件开始一直搜索到结尾。例如,假设咱们要在sonnets.txt文件中搜索'玫瑰'(插图18),十四行诗里最经常使用的意象之一。用less来作就是输入 /rose(读做“斜杠玫瑰”), 如Listing 15:less

Listing 15:使用less搜索字符串'rose'

Shake-speare's Sonnets工具

I学习

From fairest creatures we desire increase,
That thereby beauty's Rose might never die,
But as the riper should by time decease,
His tender heir might bear his memory:
But thou contracted to thine own bright eyes,
Feed'st thy light's flame with self-substantial fuel,
Making a famine where abundance lies,
Thy self thy foe, to thy sweet self too cruel:
Thou that art now the world's fresh ornament,
And only herald to the gaudy spring,
Within thine own bud buriest thy content,
And tender churl mak'st waste in niggarding:
Pity the world, or else this glutton be,
To eat the world's due, by the grave and thee.ui

IIthis

When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
/rosegoogle

Listing 15中输入/rose后结果就是在该文件中高亮显示第一次出现'rose'。你能够接着输入n指引程序搜索下一个匹配,或者N搜索上一个匹配。url

最后两个必会的less命令是G,和1G(1后面接G),分别地做用是移到文件末尾,和返回到开始。Table 4总结了我认为最重要的键组合(即:我认为你须要它才能变得厉害),可是若是你对其余命令也很感兴趣,请查看wiki对less的介绍rest

我很鼓励你习惯使用less工具查看文件。解锁的新技能一样适用于其余应用;例如:手册页(1.3章)用的less来作操做交互界面,因此经过学习less你也能够更好的在手册页中自由移动。

命令 描述 示例
up & down arrow keys 向上或向下移动一行
空格键 移至上一页
⌃F 移至上一页
⌃B 移至下一页
G 移至文件末尾
1G 回到文件开始
/<string> 在文件中搜索字符串 /rose
n 移到下个匹配的搜素结果
N 移到上个匹配的搜索结果
q 退出less
Table 4: `less` 最重要的命令

练习

1.对sonnets.txt文件运行less。向后移动3页再向前移动3页。移到文件末尾,在回到开始,最后退出。
2.搜索字符串All(区分大小写)。查找前面几个匹配项,再查找后面几个匹配项。接着移至文件的开始,数匹配项,一直数到结尾。最后比较你数的结果和运行grep All sonnets.txt | wc的结果是否相同。(咱们将在3.4章节中学习grep
3.使用less/(斜杠),找到诗中'Let me not'开始的行。这首诗中有匹配的吗?备注:按n寻找下个匹配项(若是有的话)。附加题:听听这首诗的现代版原始版,哪一个版本的韵律更好?

  1. 由于man使用了less,咱们如今能够搜索手册页了。在ls的手册页中搜索'sort'字符串,发掘经过文件大小排序的选项操做。什么命令可让文件以长表的形式列出,而且越大的文件显示在底部?备注: ls -rtl做为模型。
相关文章
相关标签/搜索