如何处理循环中的每个输出行? [英] How to process each output line in a loop?
问题描述
在运行 grep 命令后,我从文件中检索了许多行如下:
I have a number of lines retrieved from a file after running the grep command as follows:
var=`grep xyz abc.txt`
假设我得到了 10 行包含 xyz 的结果.
Let’s say I got 10 lines which consists of xyz as a result.
现在我需要处理我作为 grep 命令的结果得到的每一行.我该如何处理?
Now I need to process each line I got as a result of the grep command. How do I proceed for this?
推荐答案
一种简单的方法是不将输出存储在变量中,而是直接使用 while/read 循环对其进行迭代.
One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.
类似于:
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.
如果您需要更改循环内的变量(并使该更改在循环外可见),您可以使用 fedorqui 的回答:
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)
这篇关于如何处理循环中的每个输出行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!