我有几个包含关键字的文本文件。我必须从这些文件中选择几行并对其进行解析。下面是一个示例文件。我必须对"Customer“执行grep操作,并从文件中获取行。
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的行,并且必须对其进行解析,以仅获得时间戳(12:14:38)和数字12.14.19.9。我必须对多个文件执行此操作。所有文件都具有相同的日志结构。我已经像下面这样使用oneliner完成了这项工作。
grep Customer Neigh.log | cut -d " " -f 5- | cut -d ":" -f 1-4 | cut -d " " -f 1,8但我需要在shell脚本中执行此操作。我该怎么做呢。有人能帮上忙吗?
谢谢
发布于 2012-09-13 13:39:27
使用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发布于 2012-09-13 13:31:04
好的-
下面是一个快速的“n”脏shell脚本:
if [ $# -ne 1 ]; then
echo Please enter a filename
else
awk '/Customer/ {print $5, " ", $12}' $1
fi1)第一行检查#/命令行参数"$#“是否等于1,如果不等于1,则提示输入文件名。
2) "awk“脚本是"cut”的替代方案。当且仅当行包含"Customer“时,它才会打印出第5列和第12列。
3) "awk“命令末尾的$1是shell参数#1,即您的文件名。
发布于 2012-09-13 20:43:49
这也适用于多个文件。
awk '$0~/Customer/{print $5,$12}' *.txthttps://stackoverflow.com/questions/12399831
复制相似问题