I have a number of lines retrieved from a file after running the grep command as follows:
var=`grep xyz abc.txt`
Let’s say I got 10 lines which consists of xyz as a result.
Now I need to process each line I got as a result of the grep command. How do I proceed for this?
One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.
Something like:
There are variations on this scheme depending on exactly what you're after.
If you need to change variables inside the loop (and have that change be visible outside of it), you can use process substitution as stated in fedorqui's answer:
You can do the following
while read
loop, that will be fed by the result of thegrep
command using the so called process substitution:This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.
Note the usage of
IFS=
andread -r
according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:Regarding the process substitution, it is explained in the bash hackers page:
Often the order of the processing does not matter. GNU Parallel is made for this situation:
If you processing is more like:
and
myprogram
is slow then you can run:I would suggest using awk instead of grep + something else here.
awk '$0~/xyz/{ //your code goes here}' abc.txt