QuestionI have a number of lines retrieved from a file after running the
grep command as follows:
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 with this?HowToOne 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:
- test.sh- #!/bin/sh
- 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. A sample usage:
root@localhost:demo_bash# cat abc.txt
xyz 123
test line1
456 xyz
test line2
root@localhost:demo_bash# ./test.sh
Processing xyz 123
Processing 456 xyz