通过在一个文件的偶数行之后插入一个文件的偶数行来合并两个文件 [英] Combining two files by inserting even lines of one file after even lines of other file

查看:56
本文介绍了通过在一个文件的偶数行之后插入一个文件的偶数行来合并两个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一种有效地合并两个文件的方法.我只想在FileA的偶数行之后连接FileB的偶数行.我认为使用sed或awk可以轻松完成.任何帮助表示赞赏.

I would like to know a way to combine two files efficiently. I wanted to concatenate only even lines of FileB after even lines of FileA. I think it can be done easily with sed or awk. Any help is appreciated.

FileA:

A1
A2
A3
A4
A5
A6
.
.

FileB:

B1
B2
B3
B4
B5
B6
.
.

输出:

A1
A2
B2
A3
A4
B4
A5
.

推荐答案

这里是一种避免将其中一个文件存储在内存中的方法:

Here is an approach that avoids storing one of the files in memory:

awk -v f=FileB '{print} NR%2==0 {getline<f; getline<f; print}' FileA

工作方式:

  • -v f=FileB

    这将创建一个awk变量f,其中包含FileB的名称.

    This creates an awk variable f which contains the name of FileB.

    {print}

    这将打印从FileA读取的每一行.

    This prints every line read from FileA.

    NR%2==0 {getline<f; getline<f; print}

    如果我们在偶数行上(表示NR%2==0),那么我们将从FileB中读取两行并打印第二行.

    If we are on an even line, meaning NR%2==0, then we read two lines from FileB and print the second one.

    $ awk -v f=FileB '{print} NR%2 == 0{getline<f; getline <f; print}' FileA
    A1
    A2
    B2
    A3
    A4
    B4
    A5
    A6
    B6
    

    更多神秘版本

    Awk允许使用隐秘的速记符号执行打印:

    More cryptic version

    Awk allows prints to be performed with cryptic shorthand notations:

    awk -v f=FileB '1; NR%2{next} {getline<f; getline <f} 1' FileA
    

    在这里,1是一个条件,其计算结果为true.由于未指定 action ,因此将执行默认操作,即打印行.

    Here, 1 is a condition which evaluates to true. Since no action is specified, the default action is performed which is to print the line.

    这篇关于通过在一个文件的偶数行之后插入一个文件的偶数行来合并两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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