bash 如何将文件逐行传送到多个读取变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15442220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:27:35  来源:igfitidea点击:

How do I pipe a file line by line into multiple read variables?

bash

提问by mlebel

I have a file that contains information in two columns:

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

box1 a1
box2 a2

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

我正在尝试逐行读取此文件,read并将每个行项目放入一个变量中。

On the first pass, $awould contain box1and $bwould contain a1.

在第一遍时,$a将包含box1并且$b将包含a1

On the second pass, $awould contain box2and $bwould contain a2, etc.

在第二遍,$a将包含box2$b将包含a2等。

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

This gives me the following results:

这给了我以下结果:

box1 a1 box2 a2

When I expected the following results:

当我预期以下结果时:

box1 a1
box2 a1

How can I fix this?

我怎样才能解决这个问题?

回答by chepner

Piping into a readcommand 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 forloop or the second readcommand:

管道到read命令会导致在子shell 中设置变量,这使得它们无法访问(实际上,它们已经消失)到您的其余代码中。但是,在这种情况下,您甚至不需要for循环或第二个read命令:

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