如何将文件逐行传送到多个读取变量中? [英] How do I pipe a file line by line into multiple read variables?

查看:65
本文介绍了如何将文件逐行传送到多个读取变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列信息的文件:

I have a file that contains information in two columns:

box1 a1
box2 a2

我正在尝试将此文件逐行读取到read中,并将每个订单项都放入一个变量中.

I'm trying to read this file line by line into read and have each line items be put into a variable.

在第一遍中,$a将包含box1,而$b将包含a1.

On the first pass, $a would contain box1 and $b would contain a1.

在第二遍中,$a将包含box2,而$b将包含a2,依此类推.

On the second pass, $a would contain box2 and $b would contain a2, etc.

我要尝试实现的代码示例如下:

An example of the code that I am using to try to achieve is this:

for i in text.txt; do
    while read line; do
        echo $line | read a b;
    done < text.txt;
    echo $a $b;
done

这给了我以下结果:

box1 a1 box2 a2

当我期望以下结果时:

box1 a1
box2 a1

我该如何解决?

推荐答案

输入read命令会使变量在子shell中进行设置,这使得其余部分无法访问(实际上,它们已消失)代码.但是,在这种情况下,您甚至不需要for循环或第二个read命令:

Piping into a read command causes the variables to be set in a subshell, which makes them inaccessible (indeed, they are gone) to the rest of your code. In this case, though, you don't even need the for loop or the second read command:

while read -r a b; do
    echo "$a" "$b"
done < text.txt

这篇关于如何将文件逐行传送到多个读取变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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