Using grep -P
(requires GNU grep
):
$ grep -oP '(?<=@)\w+' File
user653434
user9659333
-o
tells grep to print only the match.
-P
tells grep to use Perl-style regular expressions.
(?<=@)
tells sed that @
must precede the match but the @
is not included in the match.
\w+
matches one or more word characters. This is what grep will print.
To change the file in place with grep
:
grep -oP '(?<=@)\w+' File >tmp && mv tmp File
Using sed
$ sed -En 's/^@([[:alnum:]]+).*/\1/p' File
user653434
user9659333
And, to change the file in place:
sed -En -i.bak 's/^@([[:alnum:]]+).*/\1/p' File
-E
tells sed to use the extended form of regular expressions. This reduces the need to use escapes.
-n
tells sed not to print anything unless we explicitly ask it to.
-i.bak
tells sed to change the file in place while leaving a backup file with the extension .bak
.
The leading s
in s/^@([[:alnum:]]+).*/\1/p
tells sed that we are using a substitute command. The command has the typical form s/old/new/
where old
is a regular expression and sed replaces old
with new
. The trailing p
is an option to the substitute command: the p
tells sed to print the resulting line.
In our case, the old
part is ^@([[:alnum:]]+).*
. Starting from the beginning of the line, ^
, this matches @
followed by one or more alphanumeric characters, ([[:alnum:]]+)
, followed by anything at all, .*
. Because the alphanumeric characters are placed in parens, this is saved as a group, denoted \1
.
The new
part of the substitute command is just \1
, the alphanumeric characters from above which comprise the user name.
Here, the s
indicates that we are using a sed substitute command. The usual form