首页 > 解决方案 > 在 unix 中使用 head 和 tail 命令从文件中提取项目

问题描述

我目前是 unix 过滤器领域的新手,并且只介绍了 unix 中的基本命令。

我有一个文件 emp.lst,其中包含我的 ubuntu 中的以下详细信息

cat emp.lst

2233|a.k.shukla|g.m.|sales|12/12/52|6000
9876|jai sharma|direcor|production|12/03/50|7000
5678|sumit chakraborty|d.g.m|marketing|19/04/43|6000
2365|barun sengupta|director|personnel|11/05/47|7800
5423|n.k. gupta|chairman|admin|30/08/56|5400
1006|chanchal singhvi|director|sales|03/09/38|6700
6213|karuna ganguly|g.m.|accounts|05/06/62|6300
1265|s.n. dasgupta|manager|sales|12/09/63|5600
4290|jayant choudhary|executive|production|07/09/50|6000
2476|anil aggarwal|manager|sales|01/05/59|5000
6521|lalit chowdary|director|marketing|26/09/45|8200
3212|shyam saksena|d.g.m.|accounts|12/12/55|6000
3564|sudhir aggarwal|executive|personnel|06/07/47|7500
2345|j.b.saxena|g.m.|marketing|12/03/45|8000
0110|v.k. agrawal|g.m.|marketing|31/12/40|9000

现在,我知道 head 提取该文件的顶部内容,而 tail 用于访问底部内容。

$head -3 emp.lst returns the first 3 rows in the file emp.lst

同样, $tail -2 emp.lst 返回文件中的最后 2 行

现在,如果我要将它们都提取在一起,即头部的前 3 行和尾部的最后 2 行?无论如何这可以实现吗?

我也试过 $head -3 emp.lst; tail -2 emp.lst \这达到了所需的结果,但我认为; 仅用于在一行中键入多个命令,也用于 $head -3 emp.lst | 尾 -2 不起作用。

标签: unixubuntu-14.04

解决方案


你可以试试

(head -3; tail -2) < emp.lst

如果你想验证你可以做的行号

cat emp.lst | nl | (head -3; tail -2) 

推荐阅读