只打印一行中的某个字符串

时间:2015-12-09 20:23:41

标签: shell awk grep

我有一个包含错误代码的日志。我需要修改我的脚本,以便它只打印错误代码,而不是紧挨着它的文本。

egrep -e 'code\ [0-9]{2}' $error_file

这是之前有效的代码。但是,显然,日志中的一些错误代码现在附加到字符串,因此我也被迫打印出这些字符。

以下是该脚本的副本:

#!/bin/sh

echo "Please enter input file name."
read input_variable
echo "You entered: $input_variable"

echo "Please enter a name of the new error file."
read error_file
touch $error_file
echo "The error file name is going to be $error_file"

echo "Processing printing only the error codes of ${input_variable} to ${error_file}."

egrep -e '\(code\ [0-9]{1,}\)' $input_variable | tee $input_variable.1 ;
awk '{print $12$13$14$15}' $input_variable.1 | tee $error_file ;

echo "Error Codes List: " ; 

egrep -e 'code[0-9]{2}' $error_file | sort -u ; 

echo "Common Errors - Count: "

echo "Code 2: " ; egrep -c 'code\ 2\)' $input_variable ;
echo "Code 10: " ; egrep -c 'code\ 10' $input_variable ;
echo "Code 11: " ; egrep -c 'code\ 11' $input_variable ;
echo "code 12: " ; egrep -c 'code\ 12' $input_variable ; 
echo "Code 14: " ; egrep -c 'code\ 14' $input_variable ;
echo "Code 20: " ; egrep -c 'code\ 20' $input_variable ;
echo "Code 23: " ; egrep -c 'code\ 23' $input_variable ; 
echo "Code 30: " ; egrep -c 'code\ 30' $input_variable ;
echo "Code 35: " ; egrep -c 'code\ 35' $input_variable ; 
echo "Total Files Transferred: " ; egrep -c '^\[[0-9]{4}/[0-9]{2}/[0-9]{2}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}\]' $input_variable ;
echo "Count Complete."
echo " " ;
echo "The following are details for each error:" ;
egrep -e 'code\ [0-9]{1,}' $input_variable ;
echo "Done. Thank you for using this error report" ;
rm $input_variable.1

以下是日志示例:

[2015/12/09 06:52:10] [12.123.456.789] [email@address.com] [R] idevs error: error in idevs protocol data stream (code 12) at io.c(1179) [sender=1.0.19]

[2015/12/09 03:01:05] [12.123.456.789] [email@address] [R] idevs error: timeout in data send/receive (code 30) at io.c(168) [sender=1.0.19]

我目前的输出是:

Error Codes List: 
(code30)atio.c(168)
datastream(code12)
Common Errors - Count:
Code 2:
0
Code 10:
0
Code 11:
0
code 12:
63
Code 14:
0
Code 20:
0
Code 23:
0
Code 30:
11
Code 35:
0
Total Files Transferred:
263
Count Complete.

The following are details for each error:
//prints each line with code\ [0-9]{1,} in the line//

请帮我打印没有额外字符的错误代码列表,所以它只是:

code12
code30

谢谢!

1 个答案:

答案 0 :(得分:0)

你可能想要:

egrep -o 'code\ [0-9]{1,}' $input_variable | sort -u

-o grep选项是关键所在。

要查找总数,我会重写您的代码,以便您只对该文件运行一次grep:

count=()
total=0

while read code num; do
    (( count[$num]++, total++ ))
done < <(egrep -o 'code\ [0-9]+' $input_variable)

for num in 2 10 11 12 14 20 23 30 35; do 
    echo "Code $num: ${count[$num]}"
done
echo "Total: $total"