Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching all words with a hashtag(#) in shell script

Tags:

bash

shell

sh

Can anyone give me a quick way to extract all hashtags in a given sentence using shell scripts.

For example: 'This is a #test that will #allow me to #remove stuff' would return #test #allow #remove

like image 468
Rohit Chopra Avatar asked Oct 31 '25 00:10

Rohit Chopra


2 Answers

You may want to try egrep -o '#[^ ]+'. The output should look like:

#test
#allow
#remove
like image 124
Matt LaFave Avatar answered Nov 02 '25 13:11

Matt LaFave


Just to provide an alternative with awk:

awk '{for (i=1; i<=NF; i++) if ($i ~ /^#/) print $i}'

And here is pure BASH way of extracting these mathes:

x=$str # your original string
while :; do
   if [[ $x =~ (\#[a-z]+)(.*)$ ]]; then
      echo "${BASH_REMATCH[1]}"
      x="${BASH_REMATCH[2]}"
   else
      break
   fi
done
like image 43
anubhava Avatar answered Nov 02 '25 14:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!