如何使用 grep 解析出 csv 中的列

how to use grep to parse out columns in csv

我有一个包含数百万行这样的日志

1482364800 bunch of stuff 172.169.49.138 252377 + many other things
1482364808 bunch of stuff 128.169.49.111 131177 + many other things 
1482364810 bunch of stuff 2001:db8:0:0:0:0:2:1 124322 + many other things
1482364900 bunch of stuff 128.169.49.112 849231 + many other things
1482364940 bunch of stuff 128.169.49.218 623423 + many other things

它太大了,我无法真正将它读入内存以供 python 解析,所以我只想将我需要的项目 zgrep 到另一个较小的文件中,但我不太擅长 grep。在 python 中,我通常会 open.gzip(log.gz) 然后将 data[0]、data[4]、data[5] 提取到一个新文件中,这样我的新文件只有 epoc和 ip 和日期(ip 可以是 ipv6 或 4)

新文件的预期结果:

1482364800 172.169.49.138 252377
1482364808 128.169.49.111 131177  
1482364810 2001:db8:0:0:0:0:2:1 124322 
1482364900 128.169.49.112 849231 
1482364940 128.169.49.218 623423 

我该怎么做 zgrep?

谢谢

到 select 列你必须使用剪切命令 zgrep/grep select 行 所以你可以像这样使用剪切命令

cut -d' ' -f1,2,4

在这个例子中,我得到第 1、2 和 4 列,其中 space ' ' 作为列的分隔符 您应该知道 -f 选项用于指定列数,-d 用于分隔符。

希望我已经回答了你的问题

我在 OSX,也许这就是问题所在,但我无法让 zgrep 过滤列。并且 zcat 在 .gz 的末尾添加了一个 .Z。这是我最后做的:

awk '{print ,,}' <(gzip -dc /path/to/source/Largefile.log.gz) | gzip > /path/to/output/Smallfile.log.gz

这让我可以过滤掉我需要的 3 列,从大文件到小文件,同时以压缩格式保留源和目标。