How can I write in nth column of a file in awk?

2020-03-30 11:34发布

For example:

abc
xyz
123
546

input.txt:

asdad
asdad
adghf
dfytr

I wanted to add the above column in 2nd column. The expected output is given below.

output.txt:

asdad  abc
asdad  xyz
adghf  123
dfytr  567

标签: shell awk
4条回答
太酷不给撩
2楼-- · 2020-03-30 12:15

paste is the easiest solution. Here's an awk example that doesn't have to store the entire first file in memory:

awk '{getline second < "example"; printf("%s\t%s\n",$0,second)}' input.txt
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-03-30 12:18

The command you're looking for is paste rather than awk. You could do it in awk but you'll probably find that paste is easier:

pax> cat qq1
asdad
asdad
adghf
dfytr

pax> cat qq2
abc
xyz
123
546

pax> paste qq1 qq2
asdad   abc
asdad   xyz
adghf   123
dfytr   546

Use paste -d' ' qq1 qq2 if you want a space rather than a tab for the delimiter.

查看更多
够拽才男人
4楼-- · 2020-03-30 12:20

In awk:

awk 'NR==FNR {x[NR] = $0} NR != FNR {print x[FNR], $0}' col1_file col2_file

Though its probably better to use paste

查看更多
Evening l夕情丶
5楼-- · 2020-03-30 12:23

You can use just bash

exec 4<file2
while read -r line1
do
 read -r line2 <&4
 echo $line $line2
 done < file1
exec 4>&-
查看更多
登录 后发表回答