bash 在一个 while 循环中从两个文件中读取行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9885338/
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
Reading lines from two files in one while loop
提问by Village
I have a file, file1.csvcontaining:
我有一个文件,file1.csv其中包含:
This
is
some
text.
I am using while read lineto cycle through each line, e.g.:
我正在使用while read line循环遍历每一行,例如:
while read line; do
echo $line
done < file1.csv
I have another file, with an identical number of lines, called file2.csv:
我有另一个文件,行数相同,称为file2.csv:
A
B
C
D
The data each line corresponds to data in the first file of the same line number.
每行的数据对应第一个文件中相同行号的数据。
- How can I modify the while loop, such so that it can print the corresponding line from
file2.csv?
- 如何修改 while 循环,以便它可以从 打印相应的行
file2.csv?
回答by Ignacio Vazquez-Abrams
Use another FD.
使用另一个FD。
while read line; do
if ! read -u 3 line2
then
break
fi
echo "$line***$line2"
done < file1.csv 3< file2.csv
回答by Mat
You could try with the pasteutility:
您可以尝试使用该paste实用程序:
$ cat one
this
is
some
text
$ cat two
1
2
3
4
$ while read a b ; do echo $a -- $b ; done < <(paste one two)
this -- 1
is -- 2
some -- 3
text -- 4
回答by kev
You can use the pastecommand:
您可以使用以下paste命令:
$ paste -d, file{1,2}.csv | while IFS=, read x y; do echo "$x:$y"; done
This:A
is:B
some:C
text.:D

