我有一个黑客脚本,它检查变大的日志文件中的某些条目。 它是perl和bash的混合 - 它工作正常 - 脚本获得它需要的东西 得到。唯一的问题是格式化" $ chdk_subscription"我试图用关键字分隔输出 ' STATS'并且'添加了'。这两个词位于每一行的开头和结尾 我想读。
#!/bin/bash
pid_foo_process=$(pgrep foo_process)
check_primary=$(grep $1 /data/foo_process-0210.$pid_foo_process.log | perl -nle 'print /(primary book \w+:\w+)/ ')
check_primary_symbol=$(grep $1 /data/foo_process-0210.$pid_foo_process.log | perl -nle 'print /primary book (\w+:\w+)/ ')
chdk_subscription=$(grep $1 /data/foo_process-0210.$pid_foo_process.log | perl -nle 'print if /(subscription for \w+:\w+.*)/ ')
echo $check_primary
echo $check_primary_symbol
IFS="STAT"
while read line
echo $line
done < echo $chdk_subscription
分手&#34; $ chdk_subscription&#34;通过&#39; IFS&#39;似乎不起作用
echo $chdk_subscription| awk -F"STATS" '{print $0}'
使用awk也不起作用 - 每次它都是一个没有换行符的大行。
STATS 10/15 08:03:09.391048 32978 (0)SB: subscription for APA:T added STATS 10/15 08:03:09.391164 32978 (0)SB: subscription for APA:P added STATS 10/15 08:03:09.391226 32978 (0)SB: subscription for APA:Z added STATS 10/15 08:03:09.391537 32978 (0)SB: subscription for APA:n added STATS 10/15 08:03:09.391599 32978 (0)SB: subscription for APA:A added STATS 10/15 08:03:09.391686 32978 (0)SB: subscription for APA:a added STATS 10/15 08:03:09.391756 32978 (0)SB: subscription for APA:K added STATS 10/15 08:03:09.391818 32978 (0)SB: subscription for APA:J added STATS 10/15 09:38:12.826928 32978 (0)SB: subscription for APA:N, XNYSAPA:3 added
我想要这样的东西,我可以阅读。
STATS 10/15 08:03:09.391048 32978 (0)SB: subscription for APA:T added
STATS 10/15 08:03:09.391164 32978 (0)SB: subscription for APA:P added
STATS 10/15 08:03:09.391226 32978 (0)SB: subscription for APA:Z added
STATS 10/15 08:03:09.391537 32978 (0)SB: subscription for APA:n added
STATS 10/15 08:03:09.391599 32978 (0)SB: subscription for APA:A added
STATS 10/15 08:03:09.391686 32978 (0)SB: subscription for APA:a added
STATS 10/15 08:03:09.391756 32978 (0)SB: subscription for APA:K added
STATS 10/15 08:03:09.391818 32978 (0)SB: subscription for APA:J added
STATS 10/15 09:38:12.826928 32978 (0)SB: subscription for APA:N, XNYSAPA:3 added
答案 0 :(得分:1)
最好使用临时文件,而不是将多行读入bash变量。
temp_file=$(mktemp)
if [ 0 -eq $? ]; then
trap 'rm -f -- "${temp_file}"' 0
else
echo "Unable to create temporary file!"
exit 1
fi
# Fill temporary file.
pid_foo_process=$(pgrep foo_process)
grep $1 /data/foo_process-0210.${pid_foo_process}.log | perl -nle 'print /(primary book \w+:\w+)/ ' >>"${temp_file}"
grep $1 /data/foo_process-0210.${pid_foo_process}.log | perl -nle 'print /primary book (\w+:\w+)/ ') >>"${temp_file}"
grep $1 /data/foo_process-0210.${pid_foo_process}.log | perl -nle 'print if /(subscription for \w+:\w+.*)/ ' >>"${temp_file}"
# Print contents.
while read line
echo "${line}"
done < "${temp_file}"
请注意,顶部的trap语句会在脚本完成时自动删除临时文件。
答案 1 :(得分:0)
awk 'BEGIN { RS=" ?STATS "} NR > 1 {print "STATS "$0}'
RS =&#34; ?STATS&#34;是分隔符,在他之后用空格捕获任何STATS,在他之前用零到一个空格。此分隔符将导致第一个空记录。 NR是记录号,因此NR> 1将忽略第一条记录。