Issue
I know similar questions have been asked around, like for example here, but I've been unable to reproduce desired results for my own needs with such examples, and I don't understand why.
I want to replace all words in a file starting with the character '@' by <@MENTION>. For example, this:
I have 6 @emailaddresses and 10% of the people don't eat sandwiches! I have six @emailaddresses and 10%... @123_Username @BAPP, you shouldn't say that! I recently called@User but he didn't answer. @Username is not a nice person! This @username guy is really cool!
Should become this:
I have 6 <@MENTION> and 10% of the people don't eat sandwiches! I have six <@MENTION> and 10%... <@MENTION> <@MENTION>, you shouldn't say that! I recently called@User but he didn't answer. <@MENTION> is not a nice person! This <@MENTION> guy is really cool!
I have tried this:
sed 's/@[a-zA-Z0-9_]*/<@MENTION>/'
But the string '@BAPP' is not taken into account, which I'd like to, and 'called@User' is taken into account, which I would prefer to avoid.
I also tried this:
sed -E -e 's/\b@[a-zA-Z0-9_]*\b/<@MENTION>/'
But for a reason I don't know the word boundaries are not taken into account...
Any help to help me understand my way around this would be much appreciated, as I'm (obviously) learning and have a limited experience with Bash. Thanks a lot in advance.
Solution
One sed
idea:
$ sed -E 's/(^|[^[:alnum:]])@[a-zA-Z0-9_]*/\1<@MENTION>/g' file
NOTE: the initial ^
was added to address the case where the desired string is at the beginning of the line.
This generates:
# assuming embedded linefeeds
I have 6 <@MENTION> and 10% of the people don't eat sandwiches! I have six
<@MENTION> and 10%... <@MENTION> <@MENTION>, you shouldn't say that! I recently
called@User but he didn't answer. <@MENTION> is not a nice person! This <@MENTION> guy
is really cool!
# assuming no embedded linefeeds
I have 6 <@MENTION> and 10% of the people don't eat sandwiches! I have six <@MENTION> and 10%... <@MENTION> <@MENTION>, you shouldn't say that! I recently called@User but he didn't answer. <@MENTION> is not a nice person! This <@MENTION> guy is really cool!
Answered By - markp-fuso Answer Checked By - Marie Seifert (WPSolving Admin)