查看linux日志文件命令

149 阅读2分钟

tail

  • tail 从文件尾部查看文件内容
  • tail -f test.log // 实时监控log的输出
  • tail -n +5 test.log // 从第5行开始输出内容

head

  • 从文件头部读取文件内容
  • head -n 10 test.log 读取文件前10条
  • head -n -10 test.log 读取文件除最后10条之外的其他日志

cat

  • cat test.log 一次性显示test.log的整个内容
  • cat > file1 创建file1文件 类比 touch file1
  • cat file1 file2 > file3 将file1内容和file2内容合并输出到file3文件中
  • tac 更cat命令一样但反向输出,即从最后一行到第一行输出
  • cat -n test.log

grep

全面搜索正则表达式匹配的内容并输出

  • cat -n test.log | grep '关键字'
  • cat test.log | grep -C 5 '关键字' 输出关键字的前后5行
  • cat test.log | grep -B 5 '关键字' 输出关键字的前5行
  • cat test.log | grep -A 5 '关键字' 输出关键字的后5行
  • grep -o '关键字' test.log|wc -l 统计关键字出现的次数

vim

  • vi test.log 进入test.log若没有文件则创建
  • a/i/o 进入可编辑模式
  • /关键字 enter键查找关键字,正向查找 查找下一个按n即可
  • ?关键字 反向查找 shift+enter 查找下一个

sed

  • sed -n '5,10p' test.log 输出5到10行日志
  • sed -n ‘/2022-10-01 14:22:20/,/2022-11-01 14:22:20/p’ test.log 查找时间段内的日志 ->可以先 grep '2022-10-01 14:22:20' test.log 查看日志中是否有该时间点

more命令

  • more 和 less 可以按照命令一页一页的向屏幕输出内容
  • more - 15 test.log //15行算作一页一页的输出
  • more +20 test.log // 从第20行开始向屏幕输出一页内容
  • more -d -15 test.log // 显示more命令的一些提示信息
  • more -c -15 test.log // 不会再有翻页的效果
  1. space 向下翻页
  2. b 向上翻页
  3. enter 翻下一行
  4. q 推出more命令

less

less 同more命令 less is more!

  1. up/down 翻上/下行
  2. pageUp翻上一页
  3. pageDown/enter 翻下一页
  4. q 退出

综合应用

  • cat -n test.log| grep "关键字" | more
  • cat -n test.log| tail -n +92 | head -n 20 查询关键字的前10行和后10行