使用awk将一个文件中的列替换为另一个文件中的列? [英] Replace column in one file with column from another using awk?

查看:79
本文介绍了使用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.NRFNR 都包含行号,区别在于 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 file f2. NR and FNR both contain line numbers with the difference being FNR gets reset to 1 when a new file is read where as NR continues to increment.
  • While we are working with f2 file, we are creating an array called a using line number (NR) as the key 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 on f1 file. NR==FNR condition will not become false as FNR will increment from 1 and NR 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 in awk true statements results in printing of the line.
  • f2 f1 is the order of files defined. Since we want to create an array from file f2 we put that first.

这篇关于使用awk将一个文件中的列替换为另一个文件中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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