并排结合特殊条件的两个文件

时间:2018-07-07 07:46:14

标签: bash awk paste

对那些头衔不好的人表示抱歉,除了示例以外,我不怎么描述。

所以我们要走了,我必须要存放以下文件:

文件1:

left1
left2
left3

文件2

right1
right2
right3

预期输出:

left1 right1
right2 left2
left3 right3

我知道我们可以使用粘贴命令将这两个文件并排合并,但是我不知道现在该如何使其像上面的输出一样。

root@s132496:~# paste -d ' ' file1 file2
left1 right1
left2 right2
left3 right3

我读了粘贴的人,但仍然不知道该怎么做。请帮我解决这个问题,从早上起一直没有运气。

在人们之前感谢您!

2 个答案:

答案 0 :(得分:3)

由于您尚未告诉我们Input_file中有多少个字段,我们是否需要始终交换第二行的字段等内容,因此仅通过查看示例即可发布此内容。

paste -d" " file1 file2 | awk 'FNR==2{$0=$2 OFS $1} 1'

答案 1 :(得分:2)

使用awk,您可以执行以下操作:

awk 'NR==FNR{a[FNR]=$0;next}FNR%2{print $0, a[FNR];next}{print a[FNR], $0}' file1 file2

展开:

awk 'NR == FNR {        # For first input file (file1)
       a[FNR] = $0      # Store the current line in a new entry in array a
       next             # and skip to the next record
     }
     FNR % 2 {          # If the line number is odd
       print $0, a[FNR] # print in one order
       next             # and skip to the next record
     }
     {                  # for the rest lines (file2 even lines)
       print a[FNR], $0 # print in opposite order
     }' file1 file2

这里的假设是file1足够小以适合内存,否则请使用cut and pipe到awk,但这仅在file1和file2的行中没有空格时才起作用。 / p>

相关问题