搜索多个关键字并在日志中打印出多个字段的匹配关键字

时间:2017-11-16 02:51:59

标签: awk grep logparser

示例log(sample.log)

<html>

<head>
  <script src="jquery-3.2.1.min.js"></script>
</head>

<body>
  <button id="sub">click here</button>
  <div id="detail"></div>

  <script>
    function fetch_data() {
      $.ajax({
        url: "select.php",
        method: "POST",
        success: function(data) {
          $('#detail').html(data);
        }
      });
    }
    $(document).ready(function() {
      $("#sub").click(function() {
        fetch_data();
      });


    });
  </script>
</body>

</html>

KEYWORDs(多个)     &#34; KOREA&#34;,&#34; OTL&#34;

我想要的结果

11:00:00 INFO KOREA AAABB DDDRR
11:00:01 INFO SWEDEN TYTY PLO
11:00:02 INFO US OIILL OTLTOL
11:00:03 INFO NORTHKOREA OTL

我只是想用awk功能。 但我失败了......

11:00:00 KOREA
11:00:02 OTL
11:00:03 KOREA OTL

2 个答案:

答案 0 :(得分:1)

关注awk可能对您有帮助。

awk '
function check(word){
  match($0,word);
  if(substr($0,RSTART,RLENGTH)){
    return substr($0,RSTART,RLENGTH)
}}
{
  val=check("KOREA");
  val=val?$1 FS val FS check("OTL"):check("OTL")?$1 FS check("OTL"):check("OTL");
  if(val){
    print val};
  val=""
}'   Input_file

答案 1 :(得分:1)

$ cat infile
11:00:00 INFO KOREA AAABB DDDRR
11:00:01 INFO SWEDEN TYTY PLO
11:00:02 INFO US OIILL OTLTOL
11:00:03 INFO NORTHKOREA OTL

$ awk -v search='KOREA|OTL' '{f=$1; s="";while(match($0,search)){s=(s?s OFS:"") substr($0,RSTART,RLENGTH);$0=substr($0,RSTART+RLENGTH)}if(s)print f,s}' infile
11:00:00 KOREA
11:00:02 OTL
11:00:03 KOREA OTL

更好的可读性:

awk -v search='KOREA|OTL' '{
            f=$1; 
            s="";
            while(match($0,search))
            {
                s  = (s?s OFS:"") substr($0,RSTART,RLENGTH);
                $0 = substr($0,RSTART+RLENGTH)
            }
            if(s)
               print f,s
            }
            ' infile