Read the output of a command into a variable
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 dogrep pattern *
which still might not be a good idea since the
*
would match all files and sub-directories in your current directory andgrep
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 sowc -l
(count the number of lines) would always return 1.
Related videos on Youtube
baccksash
Updated on September 18, 2022Comments
-
baccksash over 1 year
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.-
Rahul Patil almost 11 yearsif you post some input sample, then using awk we can make it better.
-
Rahul Patil almost 11 yearsif just want to count pattern match then use
awk '( /\|parameter1\|/ || /\|paramater2\|/ ) { n++;} END{ print n}' input.file
-
-
baccksash almost 11 yearsYou 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.
-
Jeff Hewitt almost 11 years@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.