1

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.

2 Answers2

3

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:

x=$(your_code_goes_here)

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.

jordanm
  • 42,678
Joseph R.
  • 39,549
  • 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
0

You can use this syntax:

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