【发布时间】:2012-02-22 15:43:21
【问题描述】:
请告知如何匹配仅出现在“]”字符之后的错误字符串 通过 awk 或 sed
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
我的目标是统计日志文件中仅出现在“]”字符之后的所有 ERROR 单词
remark - “]”和ERROR之间必须有一个空格或多个
【问题讨论】:
请告知如何匹配仅出现在“]”字符之后的错误字符串 通过 awk 或 sed
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
我的目标是统计日志文件中仅出现在“]”字符之后的所有 ERROR 单词
remark - “]”和ERROR之间必须有一个空格或多个
【问题讨论】:
这里是一个只有 shell 的 sn-p,它应该比使用任何外部程序(用于小文件读取)更快,因为它只使用 shell 内置。可以修改它以在守护程序模式下运行时逐个处理错误(通过将日志文件拖尾到 fifo 而不是直接读取它并修改案例条件)
不是 echo 的预期用途,但它确实将空格/制表符减少到 1 个空格
FILE="logfile"
ERRORS=0
while read LINE || [ "$LINE" ]; do
case "`echo $LINE`" in
*\]" "ERROR*)ERRORS=$(($ERRORS+1));;
esac
done < "${FILE}"
echo $ERRORS
【讨论】:
while 循环是否会比grep 快,这是值得怀疑的,你有时间吗?
这可能对你有用:
grep -c '\] \+ERROR' file
或者
grep -c '\][[:space:]]\+ERROR' file
或者
sed '/\]\s\+ERROR/!d' file | wc -l
【讨论】:
我的目标是计算所有仅出现在“]”之后的 ERROR 单词 日志文件中的字符
remark - “]”和ERROR之间必须有一个空格或多个
那么你就不需要像 awk、sed 甚至 perl 这样的核头了。 grep 是这样为你做的:
grep -Pc ']\s+ERROR' yourLogFile
小测试:
kent$ echo "[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found "|grep -Pc ']\s+ERROR'
1
【讨论】:
echo "..."|grep -Pc '...'
awk -F"] " '/ERROR/{print $2}' inputfile
[jaypal:~] echo "[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found " | awk -F"] " '/ERROR/{print $2}'
ERROR file /etc/ghy.txt not found
perl -pe 's/.*(?<=] )(.*)/$1/' inputfile
echo "[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found " | perl -pe 's/.*(?<=] )(.*)/$1/'
ERROR file /etc/ghy.txt not found
[jaypal:~/Temp] cat file
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[Mon Jan 30 21:14:01 IST 2012] ERROR file /etc/ghy.txt not found
[jaypal:~/Temp] awk -F"] " '/ERROR/{a[NR]=$2}END{print "count is " length(a)}' file
count is 9
【讨论】:
你可以的
sed -n '/] ERROR/p' infile
【讨论】:
grep 更惯用(而且可能更快)。