How to save the value of cat command in var variable?

I am trying to find the number of times a line is repeated in a file, at the same time I have to store it in a variable.

When I use the command ( cat filename | grep -c '123456789' ), it displays the score correctly, but when I use the following command, it shows that the command was not found.

 var =$(cat filename | grep -c '123456789') echo $var 

Can you tell me where I'm wrong?

+7
source share
3 answers

Do not use spaces around the = sign:

 var=$(cat filename | grep -c '123456789') 

Read at least Bash Prog Intro Howto

But you have useless use of cat , so the code is just

  var=$(grep -c '123456789' filename) 
+16
source

Remember that grep can directly read the file. You can avoid the useless use of cat .

In the example of your question, an error was not found due to a space before the equal sign. Try instead:

 var=$(grep -c '123456789' filename) 

or if you use bash:

 read var < <(grep -c '123456789' filename) 

or (for completeness) in csh / tcsh:

 setenv var `grep -c '123456789' filename` 
+6
source

Using backquotes will also work:

 varx=`( cat filename| grep -c '123456789' )` 

Ie, $ not required, you can assign the output of various commands to variables using reverse representations.

For example:

 $ pwd /home/user99 $ cur_dir=`pwd` $ echo $cur_dir /home/user99 
0
source

All Articles