打印第一行和最后一个单词的第一个单词

时间:2015-01-22 08:11:33

标签: bash shell awk grep

我试图解析SHELL中的日志文件,并希望打印第一行的第一个单词和每行的最后一个单词。

例如:

$ grep -A3 "2015-01-22T07" Test.log | grep -A3 "Messages from Summary report is"    
2015-01-22T07:36:30 | 9316 | 461 | 50 | Messages from Summary report is :[ Number of C is 1500
Total distance 10 km    
Total number of A is 2    
Number of B is 2
]
--
2015-01-22T07:37:30 | 9316 | 461 | 50 | Messages from Summary report is :[ Number of C is 1600    
Total distance 11 km    
Total number of A is 3    
Number of B is 3
]
--
2015-01-22T07:38:30 | 9316 | 461 | 50 | Messages from Summary report is :[ Number of C is 1700    
Total distance 12 km    
Total number of A is 4    
Number of B is 4    
]

预期产出:

2015-01-22T07:36:30,1500,10 km,2,2    
2015-01-22T07:37:30,1600,11 km,3,3    
2015-01-22T07:38:30,1700,12 km,4,4
抱歉,我是这个网站的新手。

cat test1.log    
2015-01-22T07:36:30 | 9316 | 461 | 50 | Messages from Summary report is :[     
Number of C is 1500    
Total distance 10 km    
Total number of A is 2    
Number of B is 2
]
--
2015-01-22T07:37:30 | 9316 | 461 | 50 | Messages from Summary report is :[     
Number of C is 1600    
Total distance 11 km    
Total number of A is 3    
Number of B is 3    
]    
--    
2015-01-22T07:38:30 | 9316 | 461 | 50 | Messages from Summary report is :[     
Number of C is 1700    
Total distance 12 km    
Total number of A is 4    
Number of B is 4    
]

重新尝试:

    # awk -v RS='\n' -v OFS=, '$1~/^[0-9]{4}-[0-9]{2}-[0-9]{2}T/ {if (s) print s; s=$1; next}
   /Total distance/{s = s OFS $(NF-1) " " $NF;next}
   NF>2{s = s OFS $NF}
   END{print s
}' test1.log

输出

,:[,1500,10 km,2,2,:[,1600,11 km,3,3,:[,1700,12 km,4,4

检查*

# head -1 test.log|cat -vte
2015-01-22T07:36:30 | 9316 | 461 | 50 | Messages from Summary report is :[ $

1 个答案:

答案 0 :(得分:1)

您可以在给定的输出上使用此awk:

awk -v RS='\r' -v OFS=, '$1~/^[0-9]{4}-[0-9]{2}-[0-9]{2}T/ {if (s) print s; s=$1; next}
   /Total distance/{s = s OFS $(NF-1) " " $NF;next}
   NF>2{s = s OFS $NF}
   END{print s
}' file
2015-01-22T07:36:30,1500,10 km,2,2
2015-01-22T07:37:30,1600,11 km,3,3
2015-01-22T07:38:30,1700,12 km,4,4