指令 head 輸出檔案前面部分內容

指令語法:

head [OPTION]... [FILE]...

參數說明:

  •  -n:指定輸出檔案前幾行內容。預設前 10 行。

範例:

[barry@rhel ~]$ head /etc/passwd

[barry@rhel ~]$ head -n 3 /etc/passwd

指令 tail 輸出檔案後面部分內容

指令語法:

tail [OPTION]... [FILE]...

參數說明:

  •  -n:指定輸出檔案最後幾行內容。預設最後 10 行。

範例:

[barry@rhel ~]$ tail -n 3 /etc/passwd

[barry@rhel ~]$ tail -n +30 /etc/passwd

→ 輸出第 30 行至最後一行之內容。

 

 

  • head (取出前面幾行)
[root@study ~]# head [-n number] 檔案 
選項與參數:
-n  :後面接數字,代表顯示幾行的意思

[root@study ~]# head /etc/man_db.conf
# 預設的情況中,顯示前面十行!若要顯示前 20 行,就得要這樣:
[root@study ~]# head -n 20 /etc/man_db.conf

範例:如果後面100行的資料都不列印,只列印/etc/man_db.conf的前面幾行,該如何是好?
[root@study ~]# head -n -100 /etc/man_db.conf

head 的英文意思就是『頭』啦,那麼這個東西的用法自然就是顯示出一個檔案的前幾行囉! 沒錯!就是這樣!若沒有加上 -n 這個選項時,預設只顯示十行,若只要一行呢?那就加入『 head -n 1 filename 』即可!

另外那個 -n 選項後面的參數較有趣,如果接的是負數,例如上面範例的-n -100時,代表列前的所有行數, 但不包括後面100行。舉例來說 CentOS 7.1 的 /etc/man_db.conf 共有131行,則上述的指令『head -n -100 /etc/man_db.conf』 就會列出前面31行,後面100行不會列印出來了。這樣說,比較容易懂了吧? ^_^

  • tail (取出後面幾行)
[root@study ~]# tail [-n number] 檔案 
選項與參數:
-n  :後面接數字,代表顯示幾行的意思
-f  :表示持續偵測後面所接的檔名,要等到按下[ctrl]-c才會結束tail的偵測

[root@study ~]# tail /etc/man_db.conf
# 預設的情況中,顯示最後的十行!若要顯示最後的 20 行,就得要這樣:
[root@study ~]# tail -n 20 /etc/man_db.conf

範例一:如果不知道/etc/man_db.conf有幾行,卻只想列出100行以後的資料時?
[root@study ~]# tail -n +100 /etc/man_db.conf

範例二:持續偵測/var/log/messages的內容
[root@study ~]# tail -f /var/log/messages
  <==要等到輸入[ctrl]-c之後才會離開tail這個指令的偵測!

有 head 自然就有 tail ( 尾巴 ) 囉!沒錯!這個 tail 的用法跟 head 的用法差不多類似,只是顯示的是後面幾行就是了!預設也是顯示十行,若要顯示非十行,就加 -n number 的選項即可。

範例一的內容就有趣啦!其實與head -n -xx有異曲同工之妙。當下達『tail -n +100 /etc/man_db.conf』 代表該檔案從100行以後都會被列出來,同樣的,在man_db.conf共有131行,因此第100~131行就會被列出來啦! 前面的99行都不會被顯示出來喔!

部分轉載自: http://linux.vbird.org/linux_basic/0220filemanager.php#file_content_3

arrow
arrow
    創作者介紹
    創作者 STORY 的頭像
    STORY

    STORY

    STORY 發表在 痞客邦 留言(0) 人氣()