Grep and print back reference

后端 未结 2 800
谎友^
谎友^ 2020-12-30 17:07

I have this iptable log:

Feb 25 10:32:48 XXX: [414645.555838] FW: DEN TCP IN=eth0 OUT= MAC=XYZ SRC=1.1.1.1 DST=2.2.2.2 LEN=40 TOS=0x00 PREC=0x00 TTL=57 ID=0          


        
2条回答
  •  鱼传尺愫
    2020-12-30 17:31

    The main issue with your example is that you are trying to return groupings, this is not possible IIUC. One way around this is to use positive look-behind (see man perlre):

    grep -oP '(?<=SRC=|SPT=)[^ ]*'
    

    Output:

    1.1.1.1
    80
    

    Here's a more portable alternative:

    grep -o 'SRC=[^ ]*\|SPT=[^ ]*' | grep -o '[^=]*$'
    

    If you want the output to be on one line, you should consider going one tool up, i.e. use Lev's answer. If you know that the output always comes in pairs, you could join the lines with paste:

    grep -oP '(?<=SRC=|SPT=)[^ ]*' | paste - -
    

    Or with xargs:

    grep -oP '(?<=SRC=|SPT=)[^ ]*' | xargs -n2
    

    Or sed:

    grep -oP '(?<=SRC=|SPT=)[^ ]*' | sed 'N; s/\n/ /'
    

提交回复
热议问题