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
How do I pipe a file line by line into multiple read variables?
提问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 read
and have each line items be put into a variable.
我正在尝试逐行读取此文件,read
并将每个行项目放入一个变量中。
On the first pass, $a
would contain box1
and $b
would contain a1
.
在第一遍时,$a
将包含box1
并且$b
将包含a1
。
On the second pass, $a
would contain box2
and $b
would 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 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:
管道到read
命令会导致在子shell 中设置变量,这使得它们无法访问(实际上,它们已经消失)到您的其余代码中。但是,在这种情况下,您甚至不需要for
循环或第二个read
命令:
while read -r a b; do
echo "$a" "$b"
done < text.txt