我的任务是做以下工作:
从stdin (可能是一个文件,但我不知道它的确切名称)没有给定名称,处理它以复制如下:
2021-07-06 - 12:45:12 - 218.251.25.78 - "Through bag smile international talk."
2021-07-06 - 12:45:12 - 213.255.42.89 - "Lay point red away member network."
^^^ ^^^ ^^^ ^^^
date hour(init) ip description这将是stdin给出的信息
Init: 2021-07-06 12:45:12
End: 2021-07-06 13:38:09
Logfile:
1625561998 218.251.25.78 CRITICAL "Through bag smile international talk."
1625573490 223.203.248.97 ERROR "Evening message suffer certainly pretty nothing she."
1625560753 36.254.92.124 DEBUG "Future suddenly guy issue Congress feeling."
1625563857 213.255.42.89 CRITICAL "Lay point red away member network."
1625560959 107.150.127.36 DEBUG "Center nothing approach."
1625579950 54.56.188.207 DEBUG "Then final simple door sell."只应使用带有关键标志的日志。
因此,我假设一段时间读行会起作用,但我不太确定如何实现grep,并获取其中的部分信息,然后将其全部连接起来。也许在另一种编程语言中会更容易一些,但在Bash中,我不知道怎么做。
**编辑是因为我以某种方式实现了对Bash的编辑。问题是,我用一个词来表示祝贺,所以如果这个词是在其他地方,而不仅仅是在$3领域,它也会匹配,这将不适合。
#!/bin/bash
while read -r line
do
if echo $line | grep -q "CRITICAL"; then
epoch=$(echo $line | gawk '{$1 = strftime("%F %T", substr($1,1,10))} 1')
hDateIp=$(echo $epoch | sed 's/CRITICAL//g' | cut -d ' ' -f1-4 | sed 's/\ /\ \-\ /g')
msg=$(echo $epoch | cut -d '"' -f2)
echo $hDateIp \"$msg\"
fi
done < file-ingest我还试图在条件中包含这一行,但没有得到任何结果,因为输出很奇怪:
if echo $line | awk -F '[]' '$3 == "CRITICAL"'发布于 2023-05-09 07:23:08
假设你想要1625561998..。Unix转换为本地时间戳,而不是打印每一行的Init时间,使用perl:
perl -MPOSIX -lne '
print strftime("%F - %T - ", localtime$1), "$2 - $3"
if /^(\d+) (\S+) CRITICAL (.*)/' (将localtime更改为gmtime以获取UTC时间而不是本地时间)。
无论如何,不应该使用外壳循环来处理文本。
发布于 2023-05-08 18:46:25
#! /bin/bash
read -r dummy date time rest
read -r ignore
read -r ignore
while read -r timestamp ip category text; do
if [ "$category" = 'CRITICAL' ]; then
printf '%s - %s - %s - %s\n' "$date" "$time" "$ip" "$text"
fi
done发布于 2023-05-09 04:58:14
Perl (仅内置,不安装模块):根据我们对您问题的评论,我将Unix epoch time转换为您在问题中指定的人类可读的格式:
|
perl -MPOSIX -ane '
CORE::say join " ", strftime("%F - %T -", localtime $F[0]), @F[1..$#F]
if $F[0] =~ /^\d+$/ and $F[2] eq "CRITICAL"
'2021-07-06 - 10:59:58 - 218.251.25.78 CRITICAL "Through bag smile international talk."
2021-07-06 - 11:30:57 - 213.255.42.89 CRITICAL "Lay point red away member network."https://unix.stackexchange.com/questions/745299
复制相似问题