Search code examples
regexbashsedgrepcut

How to use sed/grep/cut to extract numericals between two brackets?


I have a file with results as such:

   7499 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 4)
   50 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 42)
   50 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 29)
   41 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 11)
   23 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 4)
   3 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 5)
   100330 (map g (range 1 1000)),(2 2 4 4 4 4 4 4 6)

I am very new to sed and has of yet not managed to get my desired output, which I would like to be:

2 2 4 4 4 4 4 4 4
2 2 4 4 4 4 4 4 42
2 2 4 4 4 4 4 4 29
2 2 4 4 4 4 4 4 11
2 2 4 4 4 4 4 4 4
2 2 4 4 4 4 4 4 5
2 2 4 4 4 4 4 4 6

Any ideas?


Solution

  • You can use this grep:

    grep -oP '\(\K(\d+\s*)*(?=\))' file
    2 2 4 4 4 4 4 4 4
    2 2 4 4 4 4 4 4 42
    2 2 4 4 4 4 4 4 29
    2 2 4 4 4 4 4 4 11
    2 2 4 4 4 4 4 4 4
    2 2 4 4 4 4 4 4 5
    2 2 4 4 4 4 4 4 6
    

    Explanation:

    • \( - Match literal (
    • \K - Reset the match
    • (\d+\s*)* Match 0 or more combination of digits followed by 0 or more space
    • (?=\)) - Lookahead to make sure it is followed by literal )
    • -P - To use PCRE regex in grep
    • -o - To output only matched string in input