user2569803
user2569803

Reputation: 637

Bash storing grep into a variable

So i need to find a word count for the amount of words in a certain file

So in my code I have

grep -c "word" file

(that outputs the amount of instances we see in a file)

but is there any way to have it stored to a variable?

I tried

a = grep -c "word" file

and then echo $a

as well as

$a = grep -c "word file

How would I go about this?

Upvotes: 2

Views: 6241

Answers (2)

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Perhaps:

a=`grep -c "word" file`

Note the use of backquotes `. The equivalent syntax $(...) should also work.

Upvotes: 5

anubhava
anubhava

Reputation: 784998

You can store grep command line into a variable as this:

a='grep -c "word" file'

and later call it as:

bash -c "$a"

But better solution is to use BASH arrays:

arr=(grep -c "word" file)
${arr[@]}

Upvotes: 0

Related Questions