简体   繁体   English

使用带有awk或sed的列拆分日志文件

[英]Split log file using a column with awk or sed

I have a log file that looks like this: 我有一个看起来像这样的日志文件:

www.domainone.com FIX 3.3 12.12.123.1
www.domainone.com FIX 3.4 12.12.123.1
www.domainone.com FIX 2.4 12.12.123.1
www.domaintwo.com MAX 1.4 44.15.153.5
www.domaintwo.com MAX 3.2 44.15.153.5
www.domaintwo.com MAX 3.9 44.15.153.5
www.domaintwo.com MAX 12.4 44.15.153.5
www.domainthree.com NAN 3.4 34.45.144.7
www.domainthree.com NAN 2.4 34.45.144.7
www.domainthree.com NAN 3.2 34.45.144.7
www.domainthree.com NAN 3.3 34.45.144.7
www.domainthree.com NAN 1.4 34.45.144.7

And I want to run a grep, awk, sed or other bash command/script that will split that log file by the last column, so the result is 3 log files that are named using the IP without the dot. 我想运行grep,awk,sed或其他bash命令/脚本,将日志文件按最后一列进行拆分,因此结果是3个日志文件,这些文件是使用IP命名的,且不带点。 So, one of them would be 34.45.144.7.log and have 因此,其中之一将是34.45.144.7.log并具有

www.domainthree.com NAN 3.4 34.45.144.7
www.domainthree.com NAN 2.4 34.45.144.7
www.domainthree.com NAN 3.2 34.45.144.7
www.domainthree.com NAN 3.3 34.45.144.7
www.domainthree.com NAN 1.4 34.45.144.7

I was able to sort them and remove some columns from original log with with awk but no idea how to split into files using one column. 我能够使用awk对它们进行排序并从原始日志中删除一些列,但不知道如何使用一个列将其拆分为文件。

If the IP is always the fourth column, you can just use 如果IP始终是第四列,则可以使用

awk '{ filename=$4".log"; if (prev && (filename != prev)) close(prev); print >>filename; prev=filename }' ips.log

or according to @Ed Morton, even better yet 或根据@Ed Morton,甚至更好

awk '{ print >>($4".log"); close($4".log") }' ips.log

This prints the whole line into a file composed of the fourth column (IP) + ".log" 这会将整行打印到由第四列(IP)+“ .log”组成的文件中

This is with Ubuntu 12.04 and GNU awk 3.1.8. 这是与Ubuntu 12.04和GNU awk 3.1.8一起使用的。

因此,结果是使用IP命名的3个日志文件,其中不带点

awk '{f=$4; gsub(/\./,"",f);print > f".log"}' ips.log

At @OlafDietsche's request: 应@OlafDietsche的要求:

awk '{ filename=$4".log"; if (filename != prev) close(prev); print >filename; prev=filename }' ips.log

Didn't expect the comments to drag out that long or I'd have done that off the bat! 没想到评论会拖这么长的时间,否则我会立即采取行动!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM