用于搜索和导出到csv文件/ Excel工作表的Shell脚本

时间:2013-07-10 20:11:44

标签: python performance bash shell

我需要在/var/log/messages下方搜索“WAM”并将完整时间戳值导出到Excel工作表/文本文档

2013-07-09T02:22:18.535639Z user.info WebAppMgr WAM
2013-07-09T02:22:21.817372Z user.info sam SAM  ^Icom.palm.app.calculator
2013-07-09T02:22:21.818442Z user.info sam SAM  ^Icom.palm.app.settings
2013-07-09T02:22:22.746751Z user.info WebAppMgr WAM
2013-07-09T02:22:23.846636Z user.info sam SAM  ^Icom.palm.app.notes
2013-07-09T02:22:24.851727Z user.info sam SAM  ^Icom.palm.app.firstuse

对于终端输出,这将起作用

awk '/\ WAM/ {print $1"\t"}' /home/santosh/messages

我需要在文本文件/ Excel工作表输出中

WAM 
2013-07-09T02:22:18.535639Z
2013-07-09T02:22:22.746751Z

4 个答案:

答案 0 :(得分:3)

试试这个:

awk 'BEGIN{print "WAM"}/\<WAM\>/{print $1}' /home/santosh/messages > text.file

答案 1 :(得分:2)

试试这个单行:

awk 'BEGIN{v="WAM";print v}$NF==v&&$0=$1' yourfile

以你的例子:

kent$  echo "2013-07-09T02:22:18.535639Z user.info WebAppMgr WAM
2013-07-09T02:22:21.817372Z user.info sam SAM  ^Icom.palm.app.calculator
2013-07-09T02:22:21.818442Z user.info sam SAM  ^Icom.palm.app.settings
2013-07-09T02:22:22.746751Z user.info WebAppMgr WAM
2013-07-09T02:22:23.846636Z user.info sam SAM  ^Icom.palm.app.notes
2013-07-09T02:22:24.851727Z user.info sam SAM  ^Icom.palm.app.firstuse"|awk 'BEGIN{v="WAM";print v}$NF==v&&$0=$1'
WAM
2013-07-09T02:22:18.535639Z
2013-07-09T02:22:22.746751Z

答案 2 :(得分:1)

尝试

awk '/\ WAM/ {print $1"\t"}' /home/santosh/messages > ~/testOutput

您始终可以导入为Excel中由制表符分隔的文件。

答案 3 :(得分:1)

BASH:

grep WAM /var/log/messages | cut -d' ' -f1 > /home/santosh/messages

的Python:

with open('/var/log/messages') as infile, open('/home/santosh/messages', 'w') as outfile:
    outfile.write("WAM\n")
    for line in (line for line in infile if "WAM" in line):
        outfile.write(line.partition(' ')[0]
        outfile.write('\n')