我的文本文件很少,有一些关键词。我必须从这些文件中选择几行并解析它。下面是一个示例文件。我必须grep“Customer”并从文件中获取该行。
13 Sun Sep 9 12:14:38 2012 : [P] Reproducer has the 167 number
13 Sun Sep 9 12:14:38 2012 : [P] Customer has the 12.14.19.9
13 Sun Sep 9 12:14:38 2012 : [P] Customer has the 12.14.89.9
13 Sun Sep 9 12:14:38 2012 : [P] Reproducer has the 170 number
13 Sun Sep 9 12:14:38 2012 : [P] Customer has the 12.4.89.16
我必须只选择拥有Customer的行,并且必须解析它才能获得Timestamp(12:14:38)和Number 12.14.19.9。我必须为多个文件执行此操作。所有文件都具有相同的日志结构。我使用下面的oneliner
完成了这个grep Customer Neigh.log | cut -d " " -f 5- | cut -d ":" -f 1-4 | cut -d " " -f 1,8
但我需要在shell脚本中执行此操作。我怎样才能做到这一点。有人可以帮忙吗?
由于
答案 0 :(得分:1)
好的 -
这是一个快速的shell脚本:
if [ $# -ne 1 ]; then
echo Please enter a filename
else
awk '/Customer/ {print $5, " ", $12}' $1
fi
1)第一行检查#/命令行参数“$#”是否等于1.如果不是,则提示您输入文件名。
2)“awk”脚本是“cut”的替代品。当且仅当该行包含“Customer”时,它才会打印出第5列和第12列。
3)“awk”命令末尾的$ 1是shell参数#1,即你的文件名。
答案 1 :(得分:1)
这也适用于多个文件。
awk '$0~/Customer/{print $5,$12}' *.txt
答案 2 :(得分:0)
使用GNU awk
的一种方式:
for i in *.txt; do awk '/Customer/ { print $5, $NF > FILENAME".out" }' "$i"; done
如果您使用BSD awk
:
for i in *.txt; do awk '/Customer/ { out=FILENAME".out"; print $5, $NF > out }' "$i"; done