Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 檔案內容檢視指令大全:cat、tac、more、less、head、tail、nl、od 完整解析

編輯:關於 Linux

Linux 提供豐富的文字檔案檢視工具,各有適用場景。本文系統整理 cat、tac、more、less、head、tail、nl、od 等指令的語法、參數與實戰範例,助您根據檔案大小、格式與需求選擇最適合的工具。

檔案檢視指令示意

一、整檔輸出類

1. cat(concatenate)— 最常用的檢視與合併工具

cat [-AbEnTv] 檔案...

範例: cat -n /etc/hosts、cat file1 file2 > merged

2. tac — 反向輸出(最後一行先顯示)

tac /var/log/messages

二、分頁檢視類

3. more — 傳統分頁器(僅向下翻頁)

more /etc/services
# 空白鍵:下一頁 | Enter:下一行 | q:離開 | /關鍵字:搜尋

4. less — 功能強化分頁器(推薦)

less /var/log/syslog
# ↑↓:逐行 | PgUp/PgDn:翻頁 | g/G:首/尾 | /搜尋 | n/N:下/上一個 | q:離開
# less +F 相當於 tail -f(持續追蹤)

三、部分內容擷取類

5. head — 顯示前 N 行

head -n 20 /var/log/nginx/access.log
head -c 1K /path/to/file  # 顯示前 1KB

6. tail — 顯示後 N 行(含即時追蹤)

tail -n 50 /var/log/nginx/access.log
tail -f /var/log/messages          # 即時追蹤,Ctrl+C 離開
tail -f /var/log/nginx/*.log       # 同時追蹤多個檔案
tail --pid=$$ -f /var/log/syslog   # 當 PID 結束時自動停止追蹤

7. nl — 加上行號輸出

nl -ba /etc/passwd    # 所有行編號
nl -bt /etc/passwd    # 非空行編號

四、非文字/二進位檔案檢視

8. od(octal dump)— 八進位/十六進位/ASCII 轉傳

od [-t TYPE] 檔案
參數說明
-n顯示行號(含空行)
-b顯示行號(非空行)
-A顯示所有控制字元(等同 -vET)
-E顯示行尾 $
-T顯示 Tab 為 ^I
-v顯示非列印字元

輸出範例:

$ od -t c /usr/bin/passwd | head -5
0000000 177 E L F 001 001 001 \0 \0 \0 \0 \0 \0 \0 \0 \0
0000020 002 \0 003 \0 001 \0 \0 \0 260 225 004 \b 4 \0 \0 \0
...

$ od -t oCc /etc/issue | head -3
0000000 103 145 156 164 117 123 040 162 145 154 145 141 163 145 040 065
        C   e   n   t   O   S       r   e   l   e   a   s   e       5
0000020 056 062 040 050 106 151 156 141 154 051 012 113 145 162 156 145
        .   2       (   F   i   n   a   l   )  \n   K   e   r   n   e

五、補充:檔案時間戳記與 touch

類型格式範例
-t cASCII 字元od -t c /usr/bin/passwd
-t x1十六進位(1 byte)od -t x1 /bin/ls
-t o1八進位(1 byte)od -t o1 /etc/issue
-t d2十進位(2 byte)
-t f4浮點數(4 byte)
-t oCc八進位+ASCII 對照od -t oCc /etc/issue

touch 常用操作

touch file                    # 更新 atime/mtime 為現在
touch -a file                 # 僅更新 atime
touch -m file                 # 僅更新 mtime
touch -d "2023-01-01 12:00" file  # 指定時間
touch -r ref_file target_file # 參考 ref_file 時間

六、選擇指南:什麼時候用什麼?

時間類型英文觸發條件查看指令
修改時間mtime檔案內容變更ls -l(預設顯示)
狀態時間ctime檔案屬性/權限變更ls -lc
存取時間atime檔案被讀取(cat、less 等)ls -lu

熟練掌握這套檔案檢視工具組,能讓您在日誌分析、設定檔檢查、二進位偵錯等場景游刃有餘。

Copyright © Windows教程網 All Rights Reserved
需求推薦指令
快速查看小檔案全文cat
大檔案分頁閱讀、搜尋less
只看前幾行/後幾行head/tail
即時監控日誌tail -f 或 less +F
需行號參考cat -n / nl
二進位檔案分析od / xxd / hexdump
反向查看日誌tac / less (按 G 後用 ↑)