检查文件两个互补的命令是head
和tail
, 它们分别用于查看文件的开始(头部)和结束(尾部).head
命令展现了文件的前10行。(Listing 11).html
##Listing 11: 查看示例文件的开始
$ head sonnets.txt
Shake-speare's SonnetswebI服务器
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学习
一样的,tail
展现了文件的结尾后10行(Listing 12)测试
Listing 12:查看示例文件的末尾
$ tail sonnets.txt
The fairest votary took up that fire
Which many legions of true hearts had warm'd;
And so the general of hot desire
Was, sleeping, by a virgin hand disarm'd.
This brand she quenched in a cool well by,
Which from Love's fire took heat perpetual,
Growing a bath and healthful remedy,
For men diseas'd; but I, my mistress' thrall,
Came there for cure and this by that I prove,
Love's fire heats water, water cools not love.this
当你肯定只须要检查文件的开始和结尾时(也是经常使用场景),这两个命令就很是有用了。rest
顺便说一下,我已经忘记head
和tail
默认显示了多少行。因为这里默认只显示了10行,我还能够手动去数,但事实上,可使用wc
命令(“wordcount”简写,图16)来计算。日志
对wc
使用较多的场景是在整个文件上,例如,咱们能够经过wc
运行sonnets.txt
文件:code
$ wc sonnets.txt 2620 17670 95635 sonnets.txt
3个数字分别表示该文件的行数,单词数,字节数。因此这个文件有2620行(正如3.1章节末尾获得的答案),17670个单词,95635个字节。htm
如今你可能猜到了数head sonnets.txt
的行数的方法。像这样特别地,咱们能够结合head
和重定向操做符(2.1章节)建立只有该内容的文件,而后对该文件执行wc
命令,正如Listing 13:
Listing 13: 重定向
head
内容,并对其结果应用wc
命令$ head sonnets.txt > sonnets_head.txt
$ wc sonnets_head.txt
10 46 294 sonnets_head.txt
从Listing 13中能够看到head wc
有10行(46个单词,294字节)。一样的方法,也能检查tail
结果。
另外一方面,你可能也以为只为了wc
能够执行而建立中间文件不友好,确实也有个方法能够避免它,那就是使用管道技术。Listing 14展现了如何作:
Listing 14: 经过
wc
管道链接head
$ head sonnets.txt | wc
10 46 294
Listing 14的命令执行了head sonnets.txt
而后使用管道符号|
(在多数的QWERTY键盘中使用shift+ 反斜线)来管道链接wc
的结果。这能运行的缘由是wc
命令,额外接受文件名做为参数,(和多数的Unix程序样)能够经过"标准输入"(与1.2章节提到的"标准输出"相反),在这个例子中是sonnets.txt
文件中head
的输出像Listing 11.wc
程序接受这个输入而且像为文件计数样计算它,一样如Listing 13那样以行数,单词数,字节数的顺序输出。
1.经过wc
输出管道链接tail sonnets.txt
的结果,确认(像head
那样)tail
命令的输出默认显示10行。
2.运行man head
命令,学习如何查看文件的前n行。实践练习给n设置不一样的值,找到 用head
命令显示整个文件中的第一首诗(插图12).
3.根据前面对tail
的练习(使用合适的选项)只输出第一首诗的14行。备注:这条命令看起来像head -n <i> sonnets.txt | tail -n <j>
, <i>
和 <j>
表明-n
选项的数字参数。
4.tail
一个最有用的应用是运行tail -f
来查看文件是否改变。这经常使用于监测文件活动记录,例如,web服务器,一个众所周知的项目是跟踪日志文件.为模仿建立一个日志文件,执行ping learnenough.com > learnenough.log
在一个终端标签窗口。(ping
命令测试是否能链接一个服务器)在另外一个终端标签窗口中,输入命令跟踪日志文件(这时,两个标签窗口都会卡住,因此一旦掌握了tail -f
的要点,使用Box4逃离窘境)。