Living a Simple Life is a Happy Life

有饭吃,自由自在,就非常开心

How to Sort a Very Very Very Big File

| Comments

sort -uo 一个1T的文件,让最高配的google cloud instance (48 core/512G)崩溃了~~~,可惜了我的$30,白白跑了那么长时间~~~

网上搜索都是how to sort a big file,那我这个属于very very very big big big file了~~

不管是并行也好,管道也好,用了各种奇技淫巧就是敌不过人家 very very big~

不要跟我谈什么外排,归并,位图,bloom filter,redis hash去重,我就是不想折腾,最后只有分割手动外排搞定~~

把大象装进冰箱分为几步?

三步:

1
2
3
4
5
split -l 1000000000 huge-file small-chunk

for X in small-chunk*; do sort -u < $X > sorted-$X; done

sort -u -m sorted-small-chunk* > sorted-huge-file && rm -rf small-chunk* sorted-small-chunk*

小TIPS:

如果只要去重不要排序的话,尽量不要用 sort -u或者sort uniq,这个是nLog(n)的效率,让人捉急。

可以利用awk的数组是内存hash表的特性,直接awk来做,前提是你内存够大,瞎估估需要十倍于数据的内存吧:

1
cat xxxxx zzz | awk '{ if (!seen[$0]++) { print $0; } }' > xxx_zzz.uniq.txt

PS:

我后来又看了一下GNU Sort的实现描述,它说已经用了外排了,但是实际使用还是不给力,暂时迷惑中

How to Get Intersection of Two Big Files

| Comments

两个大文件,a.txt和b.txt两个文件的数据都是逐行呈现的, 如何求他们的交集、并集和差集。

用sort+uniq直接搞定:

交集

1
2
3
$ sort a.txt | uniq > aa.txt
$ sort b.txt | uniq > bb.txt
$ cat aa.txt bb.txt | sort | uniq -d

并集

1
cat a.txt b.txt | sort | uniq

差集

1
2
3
$ sort a.txt | uniq > aa.txt
$ sort b.txt | uniq > bb.txt
$ cat aa.txt bb.txt bb.txt | sort | uniq -u
  • 在开搞 bloom filter或者bitmap 或者grep -f之前可以先组合工具来一个

How to Parallel All Cmds for Linux

| Comments

grep 一个100GB的文件总是很有压力,怎么才能提速呢?

瞎优化

1
LC_ALL=C fgrep -A 5 -B 5 'xxxxx.password' allpassseed.txt
  • LC_ALL=CLC_ALL=UTF-8要块

  • 不需要正则的话,用fgrep可以提速

不过这样优化总是治标不治本,下面隆重推出linux 里面parallel all cmds的perl工具

1
cat allpassseed.txt |parallel  --pipe  --no-notice grep -f xxxxx.password

使用parallel ,和不使用parallel直接grep。结果显而易见,相差 20 倍。这比用啥 ack,ag优化效果明显多了

xargs也有一个-n的多核选项,可以作为备用

1
2
3
4
5
$ time echo {1..5} |xargs -n 1  sleep

real    0m15.005s
user    0m0.000s
sys 0m0.000s

这一条xargs把每个echo的数作为参数传给sleep ,所以一共sleep了 1+2+3+4+5=15秒。

如果使用 -P 参数分给5个核,每个核各sleep 1,2,3,4,5秒,所以执行完之后总共sleep的5秒。

1
2
3
4
5
$ time echo {1..5} |xargs -n 1 -P 5 sleep

real    0m5.003s
user    0m0.000s
sys 0m0.000s
  • 引自:

https://www.jianshu.com/p/c5a2369fa613

How to Sort Big Files

| Comments

在linux要排序一个100G的文件,压力比较大

并行解决之:

1
sort -S 50% --parallel=2 -uo list-sorted.txt list.txt

注意这一招在管道里面行不通,所以要用管道的话一定要先重定向到一个文件里面中转一下。

How to Dump Csv From Sqlite3

| Comments

1
2
3
4
5
6
7
8
#!/bin/bash

/usr/bin/sqlite3 test.db <<!
.headers on
.mode csv
.output out.csv
select username,password,email from passhouse order by site;
!