tail
用於輸出文件中的尾部內容,實際應用如下:
// 顯示文件倒數2行數據,並實時刷新新日志
tail -2f demo.log // 執行效果如下: line9 56 line0 78 // 如果你需要停止,按Ctrl+C退出 // 假如查看的日志,實時刷新的日志量非常多的話,慎用!
head
跟tail是相反的,tail是看后多少行日志;例子如下:
// 查詢日志文件中的頭10行日志; head -n 10 test.log //查詢日志文件除了最后10行的其他所有日志; head -n -10 test.log
cat
命令用於連接文件並打印到標准輸出設備上
// 顯示文件全部內容
cat demo.log // 執行結果: line1 123456 aa line2 123456 bb line3 123456 cc line4 123456 dd line5 654321 aa line6 654321 bb line7 12 line8 34 line9 56 line0 78 // 由於會顯示整個文件的內容,所以如果文件大的話,慎用! // 查詢關鍵字的日志 得到關鍵日志的行號 cat -n test.log |grep "debug" // 選擇關鍵字所在的中間一行 cat -n test.log |tail -n +92|head -n 20 // 然后查看這個關鍵字前10行和后10行的日志: // 表示查詢92行之后的日志 tail -n +92 // 20 則表示在前面的查詢結果里再查前20條記錄 head -n 20 // 分頁打印,通過點擊空格鍵翻頁 cat -n test.log |grep "debug" |more // 使用 >xxx.txt 將其保存到文件中,到時可以拉下這個文件分析,例如: cat -n test.log |grep "debug" >debug.txt
tac
關於cat命令,還有一個與之類似但寫法相反的命令:tac。寫法就是cat反過來寫
功能也是相反的,是從后往前顯示內容。示例如下:
tac demo.log
// 執行結果:
line0 78
line9 56
line8 34
line7 12
line6 654321 bb
line5 654321 aa
line4 123456 dd line3 123456 cc line2 123456 bb line1 123456 aa
more
類似cat,不過會以一頁一頁的形式顯示,按空白鍵space就往下一頁顯示,按b鍵就會往回一頁顯示
more demo.log // 執行結果(文件內容少的話,會直接顯示全部,效果跟cat一樣): line1 123456 aa line2 123456 bb line3 123456 cc --More--(15%)
less
less與more類似,但使用less可以隨意瀏覽文件(使用鍵盤上的上下箭頭),而且less在查看之前不會加載整個文件
less demo.log // 執行結果(文件內容少的話,會直接顯示全部,效果如下): line1 123456 aa line2 123456 bb line3 123456 cc line4 123456 dd line5 654321 aa line6 654321 bb line7 12 line8 34 line9 56 line0 78 demo.log (END)
當使用less命令查看日志時,還可以對關鍵字進行查找。命令如下:
// 使用斜杠(/)加關鍵字的形式,向后查找關鍵字,如查找關鍵字:123456
/123456
// 使用問號(?)加關鍵字的形式,向前查找關鍵字,如查找關鍵字:line3
?line3
// PS:跳轉到后一個關鍵字快捷鍵: N; 跳轉到前一個關鍵字:shift + N
grep
grep指令用於查找內容包含指定的范本樣式的文件,如果發現某文件的內容符合所指定的范本樣式,grep指令會把含有范本樣式的那一列顯示出來
// 查詢包含關鍵字<code>123456</code>的日志內容 grep "123456" demo.log // 執行結果 line1 123456 aa line2 123456 bb line3 123456 cc line4 123456 dd // 查詢包含關鍵字<code>123456</code>且包含<code>aa</code>的日志內容 grep "123456" demo.log | grep "aa" // 執行結果 line1 123456 aa // 查詢不包含<code>aa</code>的日志內容 grep -v "aa" demo.log // 執行結果 line2 123456 bb line3 123456 cc line4 123456 dd line6 654321 bb line7 12 line8 34 line9 56 line0 78 // 查詢包含關鍵字<code>123456</code>但不包含<code>aa</code>的日志內容 grep "123456" demo.log | grep -v "aa" // 執行結果 line2 123456 bb line3 123456 cc line4 123456 dd // 查詢包含關鍵字<code>123456</code>或<code>aa</code>的日志內容 grep "123456\|aa" demo.log 或者 grep -E "123456|aa" demo.log // 執行結果 line1 123456 aa line2 123456 bb line3 123456 cc line4 123456 dd line5 654321 aa
當你通過grep查找關鍵字,但是還是有非常多匹配的結果時,可以組合前面的less或more實現分頁顯示,示例如下:
grep "123456" demo.log | less grep "123456" demo.log | more grep "123456\|aa" demo.log | less grep "123456" demo.log | grep -v "aa" | less
