linux日志分析命令(awk, wc, uniq, sort)

418 阅读4分钟

wc

统计文件里有多少单词,多少行,多少字符。

语法

wc [-lwm]

选项与参数:
-l  :仅列出行;
-w  :仅列出多少字(英文单字);
-m  :多少字符;

举例

以下统计结果为:57行,171个字,5230个字符

需要说明的是行数是从0开始的,如果就一行,显示行数为0

image.png

sort

对指定文件中的行进行排序

语法

sort [-fbMnrtuk] [file or stdin]

选项与参数:
-f :忽略大小写的差异,例如A 与a市委编码相同;
-b :忽略最前面的空格部分;
-M :一月份的名字来排序,例如 JAN, DEC 等等的排序方法;
-n :使用 纯数字 进行排序 (默认是以文字形态来排序的);
-r :反向排序;
-u :就是 uniq, 相同的数据中,进出现一行代表;
-t :分隔符,默认使用[tab]键来分割;
-k :以哪个区间(field)来进行排序的意思;

举例

原始数据

2
3
52
6
63
2
67
3
6

image.png

image.png

uniq

去除排序过的文件中的重复行,所以为了使uniq 起作用,所有的重复行必须是相邻的。

语法

uniq [-icu]

选项与参数:
-i   :忽略大小写字符的不同;
-c  :进行计数
-u  :只显示唯一的行

举例

image.png

awk

awk 就是将文件逐行读入,然后以分隔符(默认空格)将每行切片,将切开的部分再进行各种分析处理

语法

awk  [-F field-separator ] 'commands' input-files

举例

原始数据

0aab7c8a625e2f709e560435934d4eb0, cspan_id=259873331480324348, properties={topic=abcdefg})
0aab7c8a625e2f7361c9043526e398b0, cspan_id=4459444185802421335, properties={topic=abcdefg})
0aab7c8a625e2faa7e4804355dcbc5b0, cspan_id=6201067525863407575, properties={topic=abcdefg})
0aab7c8a625e2faa80150435f9e62db0, cspan_id=6201067525863407575, properties={topic=abcdefg})
0aab7c8a625e2faa4b9c043558d8c6b0, cspan_id=6201067525863407575, properties={topic=abcdefg})
0aab7c8a625e2fabc17d04354b5a23b0, cspan_id=62370899356147701, properties={topic=abcdefg})
0aab7c8a625e2fab482f0435e96127b0, cspan_id=5196415437951744977, properties={topic=abcdefg})
0aab7c8a625e2fab120b0435babdf9b0, cspan_id=5196415437951744977, properties={topic=abcdefg})
0aab7c8a625e2fac5f180435588a42b0, cspan_id=5196415437951744977, properties={topic=abcdefg})
0aab7c8a625e2fac5e500435ed325db0, cspan_id=5196415437951744977, properties={topic=abcdefg})
0aab7c8a625e2fafcfc604350db3eab0, cspan_id=5196415437951744977, properties={topic=abcdefg})
0aab7c8a625e2fb22d9404356bed14b0, cspan_id=8309336144870248816, properties={topic=abcdefg})
0aab7c8a625e2fac5e500435ed325db0, cspan_id=3594271139193763480, properties={topic=abcdefg})
0aab7c8a625e2fb463e804354efe5cb0, cspan_id=7398322212748071916, properties={topic=abcdefg})
0aab7c8a625e2fbd058d04350ba889b0, cspan_id=857815379530969761, properties={topic=abcdefg})
0aab7c8a625e2fc090ed0435a09c6eb0, cspan_id=7398322212748071916, properties={topic=abcdefg})
0aab7c8a625e2fc068b40435649a27b0, cspan_id=7398322212748071916, properties={topic=abcdefg})
0aab7c8a625e2fc230ba043538c835b0, cspan_id=7398322212748071916, properties={topic=abcdefg})
0aab7c8a625e2fc461350435478868b0, cspan_id=7398322212748071916, properties={topic=abcdefg})
0aab7c8a625e2fc635380435d36cf0b0, cspan_id=2845810396528083534, properties={topic=abcdefg})

从这段日志中奖cspan_id取出来

image.png

统计每个cspan_id 出现的次数

image.png

统计每个cspan_id 出现的次数,并按照次数倒序排序

image.png