less
命令的核心是提供一個檢視檔案內容的互動式環境,使用者可以逐行或逐頁滾動檔案。
與其他工具(如 cat
)簡單地將整個檔案內容轉儲到控制檯不同,less 可確保輕鬆導航、搜尋功能,甚至提供文字高亮等功能。它的高效和直觀使 less 成為新手和經驗豐富的 Linux 專業人員不可或缺的命令,尤其適用於檢視大檔案或日誌。
less
命令的一般語法:
$ less [FILE]
1. 顯示行號
less -N [file]
使用 -N
選項可以在 less 命令的輸出中看到行號。
示例:
當你執行 less -N example.txt
命令時,命令 less -N
將在 less
分頁器中開啟檔案 example.
,並在每行開頭顯示行號。以下是你可能看到的輸出示例:
1 This is line one of the file. 2 Line two comes after line one. 3 The third line is this one. 4 And here's line four. 5 This example has five lines in total.
2. 搜尋檔案中的文字
less -p [word] [filename]
該命令可幫助您查詢檔案中的單詞或短語。
示例:
命令 less -p apple fruit.txt
將開啟檔案 fruit.txt
,並從第一個出現的單詞 “apple” 開始顯示內容。
假設 fruit.txt
的內容是:
orange banana apple grape apple cherry
執行 less -p apple fruit.txt
,就會從第一個出現 “apple” 的行開始,在分頁器中開啟檔案,顯示類似內容:
apple grape apple cherry
3. 顯示多個檔案
less [file1] [file2] [file3]
使用該命令逐個輸入輸入檔名,即可開啟多個檔案。
4. 減少空行
less -s [filename]
該選項可減少一系列空行,代之以單個空行。
示例:
less -s file1.txt
命令的輸出將只是 file1.txt
的內容,但會在終端中一屏一屏地顯示,並將多個連續空行壓縮為單個空行。
假設 file1.txt
包含以下內容:
This is line 1 This is line 3 This is line 5 This is line 7
如果執行 less -s file1.txt
,你會看到
This is line 1 This is line 3 This is line 5 This is line 7
5. 退出後保留終端中的內容
less -X [file]
預設情況下,退出 less
時,檔案內容將從螢幕上刪除。要在螢幕上保留這些內容,請使用 -X
選項。
更多 Linux 命令
下面羅列了最常見的一些 Linux 命令,您可以根據自己的需要查閱對應命令的詳細解析:
目錄操作 | rmdir · cd · pwd · exa · ls |
檔案操作 | cat · cp · dd · less · touch · ln · rename · more · head |
檔案系統操作 | chown · mkfs · locate |
網路 | ping · curl · wget · iptables · mtr |
搜尋和文字處理 | find · grep · sed · whatis · ripgrep · fd · tldr |
系統資訊和管理 | env · history · top · who · htop · glances · lsof |
使用者和會話管理 | screen · su · sudo · open |
此外,我們還整理 Linux 命令列大全,以幫助大家全面深入地學習 Linux。
評論留言