Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I wish grep had capture groups so I could do things like

    grep "\((\d+)\)" -print "$1" file.txt


ripgrep is a modern faster grep in Rust, some cons, many pros.

It'll do capture groups with search | replace

    # remove square brackets that surround digit characters
    $ echo '[52] apples [and] [31] mangoes' | rg '\[(\d+)]' -r '$1'
    52 apples [and] 31 mangoes


Pleasantly surprised to see an example from my ebook :)

Add `-o` option to get only the digits:

    $ echo '[52] apples [and] [31] mangoes' | rg -o '\[(\d+)]' -r '$1'
    52
    31


Congratulations (?) for making the top five google results for "ripgrep capture groups" [1].

I cite sources way more often than not, this time I got lazy after dithering over whether to go with the definitive ripgrep source page [2] or a decent looking third party(?) tutorial .. pressed for time I did neither.

[1] https://learnbyexample.github.io/learn_gnugrep_ripgrep/ripgr...

[2] https://github.com/BurntSushi/ripgrep


[1] gives some background about the issue and possible solution(s).

[1] : https://unix.stackexchange.com/questions/536657/how-to-refer...


If PCRE is supported:

    grep -oP '\(\K\d+(?=\))'
The above will give all matches in a line though. You can remove `(?=\))` part if numbers are always enclosed in `()` or if you don't care about the `)`


Lookarounds are a bit messy. It's easier to just pipe into a second grep.


certainly gets rid of one type of edge case.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: