bash 如何从 2 个文件中依次读取 1 行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8550385/
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-18 01:11:16  来源:igfitidea点击:

How to read 1 line from 2 files sequentially?

bashunix

提问by New User

How do I read from 2 files 1 line at a time? Say if I have file1 and file2 with following content:

如何一次从 2 个文件中读取 1 行?假设我有包含以下内容的 file1 和 file2:

file1:

文件 1:

line1.a    
line2.a   
line3.a   

file2:

文件2:

line1.b   
line2.b   
line3.b   

How do I get output like this -

我如何获得这样的输出 -

line1.a   
line1.b   
line2.a   
line2.b   
line3.a   
line3.b   
...
...

回答by jaypal singh

You can do it either via a pure bashway or by using a tool called paste:

您可以通过纯粹的bash方式或使用名为 的工具来做到这一点paste

Your files:

您的文件:

[jaypal:~/Temp] cat file1
line1.a
line2.a
line3.a
line4.a

[jaypal:~/Temp] cat file2
line1.b
line2.b
line3.b
line4.b

Pure Bash Solution using file descriptors:

使用文件描述符的纯 Bash 解决方案:

<&3 tells bash to read a file at descriptor 3. You would be aware that 0, 1 and 2 descriptors are used by Stdin, Stdout and Stderr. So we should avoid using those. Also, descriptors after 9 are used by bash internally so you can use any one from 3 to 9.

<&3 告诉 bash 在描述符 3 处读取文件。您应该知道 Stdin、Stdout 和 Stderr 使用 0、1 和 2 描述符。所以我们应该避免使用这些。此外,bash 内部使用 9 之后的描述符,因此您可以使用 3 到 9 之间的任何一个。

[jaypal:~/Temp] while read -r a && read -r b <&3; do
> echo -e "$a\n$b";
> done < file1 3<file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b

Paste Utility:

粘贴实用程序:

[jaypal:~/Temp] paste -d"\n" file1 file2
line1.a
line1.b
line2.a
line2.b
line3.a
line3.b
line4.a
line4.b

回答by potong

This might work for you (GNU sed though):

这可能对你有用(不过是 GNU sed):

sed 'R file2' file1

回答by k06a

C#:

C#:

string[] lines1 = File.ReadAllLines("file1.txt");
string[] lines2 = File.ReadAllLines("file2.txt");

int i1 = 0;
int i2 = 0;
bool flag = true;

while (i1+i2 < lines1.Length + lines2.Length)
{
    string line = null;
    if (flag && i1 < lines1.Length)
        line = lines1[i1++];
    else if (i2 < lines2.Length)
        line = lines2[i2++];
    else
        line = lines1[i1++];
    flag = !flag;

    Console.WriteLine(line);
}