0

hoge.txt

[email protected]
[email protected]
[email protected];es
[email protected]
[email protected]
@pepito.com 

Without group, extract email works.

$ cat hoge.txt | sed -nr '/[^@]+@[^.]+\.com$/p'
[email protected]
[email protected]

cat hoge.txt | sed -nr 's/[^@]+@[^.]+\.com$/hoge/p'
-----
hoge
hoge

However, cannot extract username part from the email with group.

cat hoge.txt | sed -nr 's/\([^@]+\)@[^.]+\.com$/hoge/g'
---
(nothing matches)

cat hoge.txt | sed -nr 's/\([^@]+\)@[^.]+\.com$/\1/p'
-----
sed: -e expression #1, char 28: invalid reference \1 on `s' command's RHS

What is wrong?

1
  • GNU sed's -r option enables extended regex mode - in which unescaped ( and ) are used for grouping and \( and \) become literal ( and ) Commented May 26, 2022 at 1:56

1 Answer 1

1

This answer focus on GNU sed.


In the gnu manual of sed theres's an explanation about the regular expression syntax and use:

5.2 Basic (BRE) and extended (ERE) regular expression

Basic and extended regular expressions are two variations on the syntax of the specified pattern. Basic Regular Expression (BRE) syntax is the default in sed (and similarly in grep). Use the POSIX-specified -E option (-r, --regexp-extended) to enable Extended Regular Expression (ERE) syntax.

In GNU sed, the only difference between basic and extended regular expressions is in the behavior of a few special characters: ‘?’, ‘+’, parentheses, braces (‘{}’), and ‘|’.

With basic (BRE) syntax, these characters do not have special meaning unless prefixed with a backslash (‘\’); While with extended (ERE) syntax it is reversed: these characters are special unless they are prefixed with backslash (‘\’).

So depending if you use BRE or ERE you have to adjust the syntax to get the desired result:

BRE:

$ sed -n 's/\([^@]\+\)@[^.]\+\.com$/\1/p' hoge.txt
tsar
cm_

ERE:

$ sed -nE 's/([^@]+)@[^.]+\.com$/\1/p' hoge.txt
tsar
cm_

Now you don't need to use cat with sed and other utilities, just reference the file at the end of the command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .