Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign grep count to variable

Tags:

grep

bash

shell

How to assign the result of

grep -c "some text" /tmp/somePath 

into variable so I can echo it.

#!/bin/bash some_var = grep -c "some text" /tmp/somePath echo "var value is: ${some_var}" 

I also tried:

some_var = 'grep -c \"some text\" /tmp/somePath' 

But I keep getting: command not found.

like image 401
JavaSheriff Avatar asked May 01 '13 22:05

JavaSheriff


People also ask

Can you use grep with a variable?

Grep works well with standard input. This allows us to use grep to match a pattern from a variable. It's is not the most graceful solution, but it works. To learn more about standard streams (STDIN, STDOUT, & STDERR) and Pipelines, read "Linux I/O, Standard Streams and Redirection".

How do you store grep output in an array?

You can use: targets=($(grep -HRl "pattern" .)) Note use of (...) for array creation in BASH. Also you can use grep -l to get only file names in grep 's output (as shown in my command).


1 Answers

To assign the output of a command, use var=$(cmd) (as shellcheck automatically tells you if you paste your script there).

#!/bin/bash some_var=$(grep -c "some text" /tmp/somePath) echo "var value is: ${some_var}" 
like image 143
that other guy Avatar answered Sep 23 '22 04:09

that other guy