You can do the following while read
loop, that will be fed by the result of the grep
command using the so called process substitution:
while IFS= read -r result
do
#whatever with value $result
done < <(grep "xyz" abc.txt)
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=
and read -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)?:
The -r option to read prevents backslash interpretation (usually used
as a backslash newline pair, to continue over multiple lines or to
escape the delimiters). Without this option, any unescaped backslashes
in the input will be discarded. You should almost always use the -r
option with read.
In the scenario above IFS= prevents trimming of leading and trailing
whitespace. Remove it if you want this effect.
Regarding the process substitution, it is explained in the bash hackers page:
Process substitution is a form of redirection where the input or
output of a process (some sequence of commands) appear as a temporary
file.