简体   繁体   English

使用awk从两个文件中写入一个两列文件

[英]write a two column file from two files using awk

I have two files of one column each 我有两个文件,每个文件只有一栏

1
2
3

and

4
5
6

I want to write a unique file with both elements as 我想写一个同时包含两个元素的唯一文件

1 4
2 5
3 6

It should be really simple I think with awk. 我认为用awk应该真的很简单。

You could try paste -d ' ' <file1> <file2> . 您可以尝试paste -d ' ' <file1> <file2> (Without -d ' ' the delimiter would be tab.) (如果没有-d ' '则分隔符为制表符。)

paste works okay for the example given but it doesn't handle variable length lines very well. 对于给定的示例, paste可以正常工作,但是它不能很好地处理可变长度的线。 A nice little-know core-util pr provides a more flexible solution: 一个不错的鲜为人知的core-util pr提供了更灵活的解决方案:

$ pr -mtw 4 file1 file2
1 4
2 5
3 6 

A variable length example: 可变长度示例:

$ pr -mtw 22 file1 file2
10         4
200        5
300,000,00 6

And since you asked about awk here is one way: 既然您问过awk这就是一种方法:

$ awk '{a[FNR]=a[FNR]$0" "}END{for(i=1;i<=length(a);i++)print a[i]}' file1 file2
1 4 
2 5 
3 6

Using awk 使用awk

awk 'NR==FNR { a[FNR]=$0;next } { print a[FNR],$0 }' file{1,2}

Explanation: 说明:

  • NR==FNR will ensure our first action statement runs for first file only. NR==FNR将确保我们的第一个操作语句仅对第一个文件运行。
  • a[FNR]=$0 with this we are inserting first file into array a indexed at line number a[FNR]=$0 ,我们将第一个文件插入到数组中,行号为索引
  • Once first file is complete we move to second action 完成第一个文件后,我们移至第二步
  • Here we print each line of first file along with second file 在这里,我们打印第一个文件的每一行以及第二个文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM