This question already has an answer here:

I am making a bash script but I'm totally new and got lost.

I've made this code

cat * | grep "|*parameter1*|" | grep "|*parameter2*|" | cut -f 8,11,12,15,21,23,34 -d "|" | wc -l

which works just fine, but I need to read the wc -l output into a variable so I can make an average after that with another bash command. Then, print out that average and make it readable to the user.

marked as duplicate by Gilles, manatwork, Renan, user26112, jasonwryan Jul 11 '13 at 18:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    if you post some input sample, then using awk we can make it better. – Rahul Patil Jul 10 '13 at 16:10
  • if just want to count pattern match then use awk '( /\|parameter1\|/ || /\|paramater2\|/ ) { n++;} END{ print n}' input.file – Rahul Patil Jul 10 '13 at 16:43

To answer your direct question, you need to wrap your code in a $() sequence so that its output can be assigned to a variable. Like so:


That said, I have a few notes about your one-liner:

  • Why the leading cat *? This seems to be a useless use of cat. You can directly do

    grep pattern *

    which still might not be a good idea since the * would match all files and sub-directories in your current directory and grep will throw a warning if you ask it to search in a directory without supplying the -r (recursive) option. Using the * may or may not be suitable depending on your use case.

  • I'm not sure what the wc -l at the end is intended for: cut doesn't print its output on several lines so wc -l (count the number of lines) would always return 1.

  • You were right, this is what I needed. I used {cat} because I am gonna write the result into a .txt as well. And that's the reason for the {cut} too The {wc -l} in this case is needed because i am searching for logs with a specific pattern. – baccksash Jul 10 '13 at 22:34
  • @baccksash Again, I doubt that wc -l is the right choice here. Maybe if you gives us more information on what you're trying to accomplish, we can help you achieve it in an easier way. – Joseph R. Jul 10 '13 at 22:42

You can use this syntax:

var=$(cat * | grep "|*parameter1*|" | grep "|*parameter2*|" | cut -f 8,11,12,15,21,23,34 -d "|" | wc -l)

Not the answer you're looking for? Browse other questions tagged or ask your own question.