Reputation: 853
I'm trying to find the number of times a string is repeated in a file, at the same time i've to store it in a variable.
When i use the command (cat filename | grep -c '123456789'
) , it displays the count correctly but when i use the below command it shows as command not found.
var =$(cat filename | grep -c '123456789')
echo $var
Can u let me know where i'm wrong ?
Upvotes: 8
Views: 43224
Reputation: 1
Don't use spaces around the =
sign:
var=$(cat filename | grep -c '123456789')
Read at least the Bash Prog Intro Howto
But you've got a useless use of cat
so code simply
var=$(grep -c '123456789' filename)
Upvotes: 16
Reputation: 46826
Remember that grep can read the file directly. You can avoid useless use of cat.
In the example in your question, the command not found error occurs because of the space before the equals sign. Try this instead:
var=$(grep -c '123456789' filename)
or if you're using bash:
read var < <(grep -c '123456789' filename)
or (for completeness) in csh/tcsh:
setenv var `grep -c '123456789' filename`
Upvotes: 5
Reputation: 143047
Using backquotes will also work:
varx=`( cat filename| grep -c '123456789' )`
I.e., the $
is not required, you can assign the output of various commands to variables through the use of backquotes.
For instance:
$ pwd
/home/user99
$ cur_dir=`pwd`
$ echo $cur_dir
/home/user99
Upvotes: 1