Search code examples
regexlinuxbashgrepcut

Grep n'th element


I have a log file in which i need to grep some specific fields.

The log file uses spaces for separating the elements in lines, but a line may also contain a sentence with quotation marks. I need to grep the n'th element.

A line in the file could look like this:

2018-05-01 12:05:16 9 10.10.10.20 ab bc - - foobar - "bar foo" - "barbar foo" cd ed
2018-05-01 12:05:16 9 10.10.20.20 ab bc - - foobar - "barfoo" abc "barbar foo" cd ed

I would like to grep the 13th element, for 1st line it is "barbar foo" and the 2nd line it is "abc foo"

So a

cut -d " " -f 13 

wont do it, as 1st line 11th element has "bar foo" and the 2nd line 11th element is "barfoo"

Hope this makes sense! All help is appreciated


Solution

  • Using GNU awk:

    $ awk 'BEGIN{FPAT="([^ ]*)|(\"[^\"]+\")"}{print $13}' file
    "barbar foo"
    "barbar foo"
    

    More on FPAT here.