Awk print matched column if exists else print not found

后端 未结 3 1989
终归单人心
终归单人心 2021-01-24 03:47

My text file looks like below

date=\"2017-10-10\" ip=192.168.1.1:22 inbound=100 outbound=100
date=\"2017-10-10\" ip=192.168.1.1:22 inbound=100
date=\"2017-10-10         


        
3条回答
  •  甜味超标
    2021-01-24 04:15

    Input

    $ cat file
    date="2017-10-10" ip=192.168.1.1:22 inbound=100 outbound=100
    date="2017-10-10" ip=192.168.1.1:22 inbound=100
    date="2017-10-10" ip=192.168.1.1:22  outbound=100
    

    Output

    $ awk '{if(match($0,/inbound=[0-9]+/)){s=substr($0,RSTART,RLENGTH); print substr(s,index(s,"=")+1);next}print 0,"Not Found"}' file
    100
    100
    0 Not Found
    

    Explanation

    awk '{
    
        # Search for word inbound=[0-9]+ in record/line/row, if found then
        if(match($0,/inbound=[0-9]+/))
        {
            # Extract word
            s=substr($0,RSTART,RLENGTH)
    
            # Print value which is after "="  
            print substr(s,index(s,"=")+1)
    
            # Go to next line
            next
        }
    
          # If above condition is not true then word inbound not found in line/row/record
    
          print 0,"Not Found"
      }
     ' file
    

提交回复
热议问题