从日志文件中搜索并打印特定数字

时间:2014-01-03 07:18:45

标签: linux bash shell sed awk

我有一个带有此结构的 log.text 文件:

user                session             login_time          application         database            db_connect_time     request             request_time        connection_source   connection_ip       request_state
+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------
 admin                                 0                   9                                                           0 none                                  0 Not Requested*      a00:bf32::                    
 admin                         989855740                1335 DRRDEVMH            DRRPRODB                           1201 none                                  0 Not Requested       a00:8a45::                    
 admin                        1768947706                 932 test                test                                916 none                                  0 Not Requested       a00:94b6::                    

 WARNING - 1241024 - Possible string truncation in column 1.
 WARNING - 1241028 - Output column defined with warnings.
 WARNING - 1241024 - Possible string truncation in column 9.
 WARNING - 1241028 - Output column defined with warnings.
 WARNING - 1241024 - Possible string truncation in column 10.
 WARNING - 1241028 - Output column defined with warnings.
 OK/INFO - 1241044 - Records returned: [3].

正如我们在log.txt的最后一行中看到的那样,有一个字符串Records returned: [3]。那个数字3是我的目标,提取该数字(在这种情况下为3)我想在一个单独的文件中打印下一行。

The total records returned = 3

我正在使用:

sed -n 's@^.*Records returned.*[\(.*\)$@\1@p' log.txt > out.txt

但它没有给出结果。我在这里犯了什么错,拜托?

4 个答案:

答案 0 :(得分:3)

你需要逃避[,试试这个

sed -n 's@^.*Records returned.*\[\(.*\)\].*$@\1@p' log.txt > out.txt

修改
如果你想打印出像这样的字符串

  

返回的总记录数= 3

只需在The total records returned =之前添加\1,因此脚本将为

sed -n 's@^.*Records returned.*\[\(.*\)\].*$@The total records returned = \1@p' log.txt > out.txt

答案 1 :(得分:2)

使用awk

awk -F "[][]" '$0~t  {print "The total",t,"=",$2}' t="Records returned" log.txt > out.txt
cat out.txt    
The total Records returned = 3

答案 2 :(得分:1)

sed -n '$ s/.*\([[:digit:]]\{1,\}\)].$/The total records returned = \1/p'

假设,作为您的样本和解释状态,该信息位于具有此格式的最后一行。

答案 3 :(得分:1)

在Test.txt文件中假设您的数据然后您只需使用下面的命令

echo "Total Records Count = `cat Test.txt | tail -n 1 | cut -d '[' -f2 | cut -d ']' -f1` "

总记录数= 3

enter image description here