本文介绍大日志分割的几种方法。
当日志容量上G的时候,用vi查看具体内容效率就会变得特别低,这个时候就需要将大日志进行分割。
为了比较各种分割方法的效果,我选取的测试日志基本信息如下:
# ls -lrth test.log
-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log
# wc -l test.log
8856340 test.log
- 1
- 2
- 3
- 4
1. split方法分割
split命令专门用来将一个大文件分割成很多个小文件,我把split命令的选项做一个简要说明
选项 | 含义 |
---|---|
-b | 分割后的文档大小,单位是byte |
-C | 分割后的文档,单行最大byte数 |
-d | 使用数字作为后缀,同时使用-a length指定后缀长度 |
-l | 分割后文档的行数 |
为了尽量保证日志的可读性,我们按行分割大日志文件,并且指定分割后的文件的前缀和后缀
#后缀是数字,占两位,前缀是test.log
split -l 1000000 test.log -d -a 2 test.log
#分割之后的结果
ls -lrth
总用量 1.3G
-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log00
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log01
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log02
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log03
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log04
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log05
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log06
-rw-r--r-- 1 root root 73M 5月 30 20:55 test.log07
-rw-r--r-- 1 root root 64M 5月 30 20:55 test.log08
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
2. dd分割
dd bs=1M count=300 if=test.log of=newlog.1
dd bs=1M count=300 if=test.log of=newlog.2 skip=300
dd bs=1M count=300 if=test.log of=newlog.3 skip=600
- 1
- 2
- 3
分割后的效果
ls -lrth
总用量 1.3G
-rw-r--r-- 1 root root 645M 5月 30 20:42 test.log
-rw-r--r-- 1 root root 300M 5月 30 21:07 newlog.1
-rw-r--r-- 1 root root 300M 5月 30 21:07 newlog.2
-rw-r--r-- 1 root root 45M 5月 30 21:07 newlog.3
- 1
- 2
- 3
- 4
- 5
- 6
在上面使用的命令中,bs代表数据块的大小,count表示复制的块数,if表示输入文件,of表示输出文件。
这个命令不能一下就把文件分割到我们想要的状态,而且很有可能一行日志被分到两个文件中。
3. head+tail分割
用这两个命令获取文件部分内容,然后重定向就能实现文件分割,但是限制也挺多,只能把文件分成两部分,如果文件特别大,想要达到预期的效果,就要一直分割下去。
head/tail -n $行数 test.log > newlog
因为这两个命令都比较熟悉,不再多讲。
4. sed实现分割
实现原理就是用sed截取特定行之间的内容,然后进行重定向。
sed -n '1,2000000p' test.log > test.log.1
sed -n '2000001,4000000p' test.log > test.log.2
sed -n '4000001,6000000p' test.log > test.log.3
sed -n '6000001,8000000p' test.log > test.log.4
sed -n '8000001,$p' test.log > test.log.5
- 1
- 2
- 3
- 4
- 5
$表示最后一行,这个如果分割过多,也需要一个循环。
5. awk实现分割
实现原理和sed差不多,因为使用awk不多,这里只举一个小例子:
awk ‘{if (NR<120000) print $0}’ test.log > a.txt
awk ‘{if (NR>=120000) print $0}’ test.log > b.txt
- 1
- 2
还是split用得舒服。
来源:https://blog.csdn.net/u012949658/article/details/72812236