使用awk将一个文件中的列替换为另一个文件中的列? [英] Replace column in one file with column from another using awk?
本文介绍了使用awk将一个文件中的列替换为另一个文件中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个文件:
f1:
111 aaa 444
222 bbb 555
333 ccc 666
f2:
111 333 000 444
222 444 111 555
333 555 555 666
如何使用 awk 将f1"中的第二列替换为f2"中的第三列?
How can I replace second column in "f1", with third column from "f2" using awk?
推荐答案
尝试:
awk 'FNR==NR{a[NR]=$3;next}{$2=a[FNR]}1' f2 f1
输出:
111 000 444
222 111 555
333 555 666
以上代码说明:
FNR==NR
允许您一次处理一个完整的文件.在本例中,它是文件f2
.NR
和FNR
都包含行号,区别在于FNR
在读取新文件时重置为 1,其中NR
继续递增.- 当我们使用
f2
文件时,我们正在创建一个名为a
的数组,使用行号 (NR
) 作为key
和第三列 ($3
) 作为值.next
允许我们跳过动作块的其余部分. - 一旦
f2
文件结束,我们就开始处理f1
文件.NR==FNR
条件不会变为假,因为FNR
将从 1 开始递增,而NR
不会.所以只有第二个动作块{$2=a[FNR]}
将被处理. - 这个块的作用是通过查找行号将第二列值重新分配给数组值.
1
最后打印该行.它返回 true,并且在awk
true 语句中会打印该行.f2 f1
是定义的文件顺序.因为我们想从文件f2
创建一个数组,所以我们把它放在第一位.
FNR==NR
allows you to work with one entire file at a time. In this case it is the filef2
.NR
andFNR
both contain line numbers with the difference beingFNR
gets reset to 1 when a new file is read where asNR
continues to increment.- While we are working with
f2
file, we are creating an array calleda
using line number (NR
) as thekey
and third column ($3
) as the value.next
allows us to skip the rest of the action block. - Once
f2
file ends, we start to work onf1
file.NR==FNR
condition will not become false asFNR
will increment from 1 andNR
won't. So only second action block{$2=a[FNR]}
will be worked upon. - What this block does is it re-assigns second column value to array value by looking up the line number.
1
at the end prints the line. It returns true, and inawk
true statements results in printing of the line.f2 f1
is the order of files defined. Since we want to create an array from filef2
we put that first.
这篇关于使用awk将一个文件中的列替换为另一个文件中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文