0

To make it really simple, I must use a regex to select string in a complex file. I would like to "save" in a file some part of the regex selection. So I use capturing groups and... I don't know how to use th result.

For ex: list.txt :

abc 123 def 456

Here my regex with capture group :

(\d{3}) (\w{3})

The shell command with grep for example (can be something else, I don't care):

egrep '(\d{3}) (\w{3})' list.txt

How do I save or use every \d{3} and \w{3} results? I can't just use

egrep '\d{3}' > digit.txt

Because the capture group is just a small part of a bigger regex

Thanks

A D
  • 25
  • 6
  • Maybe [this](https://stackoverflow.com/q/2777579/1707353) will help? – Jeff Holt Sep 14 '18 at 19:58
  • 1
    `egrep` *isn't* a shell regex at all -- grep is an external command, not part of the shell, and the shell has no access to its state. Native shell regex syntax is more like `re='([[:digit:]]{3} ([^[:space:]]+)'; [[ $str =~ $re ]]`, which will save your capture groups in the shell variable `BASH_REMATCH`. (Note that the syntax there is baseline ERE -- `\d` and `\w` are extensions taken from PCRE; some platforms offer them, others don't, and it's unsafe to assume they'll be available since which features are available in native-shell regexes depends on the local C library). – Charles Duffy Sep 14 '18 at 20:40
  • See [Pure bash replacement capturing groups](https://stackoverflow.com/questions/40773834/pure-bash-replacement-capturing-groups) – Charles Duffy Sep 14 '18 at 20:45
  • Could you [edit your question](https://stackoverflow.com/posts/52338465/edit) and add some lines and expected result? – Toto Sep 15 '18 at 09:58

2 Answers2

0

sed will work too:

sed 's/.*\([0-9][0-9][0-9] [a-z][a-z][a-z]\).*/\1/' ./list.txt

Sorry, my old vm with ubuntu doesn't seem to support the \d or \w shortcuts.

Gary_W
  • 9,933
  • 1
  • 22
  • 40
  • That's not just about your "old vm" -- `\d` or `\w` aren't part of even the very latest version of the POSIX ERE standard; they aren't *supposed* to work. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html – Charles Duffy Sep 14 '18 at 20:43
  • It was just a really simple example. I use capture groups because my regex is big and complex and exporting the whole result will not help me I think. The big regex is here to select some lines in a big file. The capture group to select small part of those big lines. I can maybe find something with grep and cut... – A D Sep 14 '18 at 20:56
  • @CharlesDuffy Thanks for the info – Gary_W Sep 14 '18 at 21:34
0

I found a solution with ${BASH_REMATCH[1]} and ${BASH_REMATCH[2]}

A D
  • 25
  • 6