1

I need help setting the output of the grep command below as a variable for each line.

    while read line; do 
        grep -oP '@\K[^ ]*' <<< $line
    done < tweets

Above displays what I want like this:

lunaluvbad

Mags_GB

And so on...

However if I would do something like:

    while read line; do
        usrs="grep -oP '@\K[^ ]*' <<< $line"
    done < tweets

    echo $usrs

It displays weird result, and certainly not the result I'm looking for. I need $usrs to display what I had mentioned above. Example:

lunaluvbad

Mags_GB

0

2 Answers 2

2

No need for a loop at all. grep will loop over the lines of the input anyway:

usrs=$(grep -oP '@\K[^ ]*' tweets)
Sign up to request clarification or add additional context in comments.

3 Comments

This almost displays what I want, but the output is not displayed on its own line. Every word needs to be on its own line. Have any ideas?
@RydallCooper Use quotes when you print the variable: echo "$usrs"
@RydallCooper: If you just want the output, grep -oP '@\K[^ ]*' tweets is all you need. If you want to do further processing on the output, tell us what you are trying to do.
2

Make use of BASH arrays and command substitution like this:

users=()
while read -r line; do
    users+=( "$(grep -oP '@\K[^ ]*' <<< "$line")" )
done < tweets

OR else using process substitution:

users=()
while read -r line; do
    users+=( "$line" )
done < <(grep -oP '@\K[^ ]*' tweets)

printf "%s\n" "${users[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.