JohnnyLoo
JohnnyLoo

Reputation: 927

Printing all words that start with "@" using sed in BASH

I have a file with a lot of text, but I want to print only words that contain "@" at the beginning. Ex:

My name is @Laura and I live in @London. Name=@Laura. City=@London

How can I print all words that start with @?.I did this the following and it worked, but I want to do it using sed. I tried several patters, but I cannot make it print anything.

grep -o -E "@\w+" file.txt

Thanks

Upvotes: 0

Views: 3631

Answers (1)

ShellFish
ShellFish

Reputation: 4551

Use this command:

sed 's/[^@]*\(@[^ .]*\)/\1\n/g' file.txt

Explanation: we invoke the substitution command of sed. This has following structure: sed 's/regex/replace/options'. We will search for a regex and replace it using the g option. g makes sure the match is made multiple times per line.

We look for a series of non at chars followed by an @ and a number of non-spaces @[^ ]*. We put this last part in a group \(\) and sub it during the replacement \1.

Note that we add a newline at the end of each match, you can also get the output on a single line by omitting the \n.

Upvotes: 3

Related Questions