views:

78

answers:

5

Hey there !

I'm trying to automate a proces which I have to do over and over again in which I have to parse the output from a shell function, look for 5 different things, and then put them on a file

I know I can match patterns with grep however I don't know how to store the result on a variable so I can use it after :( I also have to parse this very same output to get the other 5 values

I have no idea on how to use the same output for the 5 grep's i need to do and then store it to 5 different variables for after use

I know i have to create a nice and tidy .sh but I don't know how to do this

Currently im trying this

#!/bin/bash 
data=$(cat file) 
lol=$(echo data|grep red) 
echo $lol 

not working , any ideas?

+1  A: 

You can use the following syntax:

VAR=$(grep foo bar)

or alternatively:

VAR=`grep foo bar`
Michael Foukarakis
can I call grep on another var?such asVAR=$(grep foo bar)VAR2=$(VAR | grep other bar)?
PERR0_HUNTER
No, but you can either use regexp matching on variables or (less preferable to me) write a variable to a file and grep that.
Michael Foukarakis
No but you can echo that var and grep the output of echo: `VAR2=$(echo $VAR|grep other)`. Notice the `$VAR`.
slebetman
Yes you can.VAR1=$(grep foo bar)VAR2=$(grep baz bat)for example...
GodEater
+1  A: 

The easiest thing to do would be to redirect the output of the function to a file. You can then run multiple greps on it and only delete the file once you are done with it.

To save the output, you want to use command substitution. This runs a command and then converts the output into command line parameter. Combined with variable assignment you get:

variable=$(grep expression file)
R Samuel Klatchko
+2  A: 

you should show some examples of what you want to do next time..

assuming you shell function is called func1

func1(){
  echo "things i want to get are here"
}

func1 | grep -E "things|want|are|here|get" > outputfile.txt

Update:

your code

#!/bin/bash 
data=$(cat file) 
lol=$(echo data|grep red) 
echo $lol 

practically just means this

lol=$(grep "red" file)

or

lol=$(awk '/red/' file)

also, if you are considering using bash, this is one way you can do it

while read -r myline
do 
    case "$myline" in
      *"red"* ) echo "$myline" >> output.txt
    esac
done <file
ghostdog74
+1  A: 

Your second line is wrong. Change it to this:

lol=$(echo "$data"|grep red)
Emil Vikström
A: 

use egrep istead of grep.

variable=$(egrep "exp1|exp2|exp3|exp4|exp5" file)

Venkataramesh Kommoju
`grep` allows disjunctive rexps using "\|" to separate alternatives. It is `fgrep` that has fixed strings.
Charles Stewart