1

This

$echo '| foo | bar | baz |' | sed 's@^|[^|]*|\([^|]*\)|.*@\1@'

return bar as desired. How would I do the same with opt -E?

https://www.gnu.org/software/sed/manual/html_node/Extended-regexps.html

1

Try:

$ echo '| foo | bar | baz |' | sed -E 's@^\|[^|]*\|([^|]*)\|.*@\1@'
 bar

Notes:

  1. In extended regex, groups are made with (...) instead of \(...\).

  2. In extended regex, | generally means alternation. To interpret it as a character, it needs to be escaped. (The exception to this rule is inside [...] where | is just a regular character.

Alternative: using awk

$ echo '| foo | bar | baz |' | awk -F\| '{print $3}'
 bar 
  • 1
    I had tried groups without \ but forgot \|. Yeah, awk more straightforward. – Erwann Jun 26 '19 at 22:14
  • @Erwann Yes, that's understandable. I try to use ERE all the time just so I don't have to keep track of that stuff. – John1024 Jun 26 '19 at 22:22
  • 1
    @Erwann Try: echo " , year={1964}}" | sed -E 's/.*year=\{(.+[^}]).*/\1/' – John1024 Jun 29 '19 at 19:14
  • 1
    @Erwann Three points: (a) The capture group needed to include [^}]. So, we needed (.+[^}]) instead of (.+)[^}]. Otherwise, the last digit would be missing. (b) we needed to throw away both }, not just the first. So, we replaced \} with .*. As the least important point, (c) inside [...], } is just a regular character and doesn't need to be escaped. [^\}] actually means any character except } or ``. – John1024 Jun 29 '19 at 20:09
  • 1
    @Erwann If you add things after the }, then use sed -E 's/.*year=\{([^}]*).*/\1/' – John1024 Jun 29 '19 at 23:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.