Thursday, July 12, 2018

bash - How to process each line received as a result of grep command



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?


Answer



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:




grep xyz abc.txt | while read -r line ; do
echo "Processing $line"
# your code goes here
done


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:




while read -r line ; do
echo "Processing $line"
# your code goes here
done < <(grep xyz abc.txt)

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...