在一个文件中与来自另一个用awk替换列列? [英] Replace column in one file with column from another using awk?

查看:138
本文介绍了在一个文件中与来自另一个用awk替换列列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件:

f1:
111 aaa 444
222 bbb 555
333 ccc 666

f2:
111 333 000 444
222 444 111 555
333 555 555 666

如何能取代F1第二列,与第三列从F2用awk?

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

以上code的说明:


  • FNR == NR 允许你在一个时间与一个整个文件的工作。在这种情况下,它是文件 F2 NR FNR 都包含有不同之处的行号 FNR 当读取一个新的文件,其中为 NR 继续递增被重置为1。

  • 当我们正在使用 F2 文件,我们正在创建一个名为 A 使用行号(<$数组C $ C> NR )为和第三列( $ 3 )作为值。 接下来让我们跳过动作块的其余部分。

  • F2 文件结束,我们开始对 F1 文件工作。 NR == FNR 状况不会成为虚假的 FNR 从1递增, NR 不会。因此,只有第二个动作块 {$ 2 = [FNR]} 将在工作。

  • 什么块所做的事是通过查找行号重新分配第二列的值数组值。

  • 1 在最后打印行。它返回true,并在 AWK 在该行打印真实的陈述的结果。

  • 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天全站免登陆