如何在循环中处理每条输出线? [英] How to process each output line in a loop?

查看:33
本文介绍了如何在循环中处理每条输出线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行 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.

如果您需要在循环内更改变量(并使更改在外部可见),则可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆