Tareekz
Tareekz

Reputation: 23

Bash find hashtags from string

I'm new to shell scripting and I'm trying to find all hashtags from a string using grep, this is what I have but it only works for alphanumeric characters

echo '<span><span>#😀fooFOO0</span></span>' | grep -o '#[a-zA-Z0-9]'

Upvotes: 2

Views: 742

Answers (2)

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43401

The following command print a line for each hashtag found:

❯ echo '<span><span>#😀fooFOO0</span>#foo #bar</span>' | grep --fixed-strings --only-matching '#'
#
#
#

Options

  • -F, --fixed-strings

    Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated by newlines, any of which is to be matched.

  • -o, --only-matching

    Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Warning: --count or -c won't give the number of hashtags (3) but the number of lines containing one (only 1 here).

Upvotes: 0

Philippe
Philippe

Reputation: 26537

If the hashtag finishes before </span>, you can do

echo '<span><span>#😀fooFOO0</span></span>' | grep -Po '#.*?(?=<)'

.*? means non-greedy search.

(?=<) is look-ahead.

Upvotes: 1

Related Questions