用另一个文件中的值替换文件中的字符串 [英] replace string in a file with value from another file

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

问题描述

我有两个文件.其中一个定义了一组数值对,如下所示 (fileA):

I have two files. One of them defines a set of number-value pairs as follows (fileA):

 1  asm
 2  assert
 3  bio
 4  bootasm
 5  bootmain
 6  buf
 7  cat
 8  console
 9  defs
10  echo

另一个文件包含一堆值对,如下(fileB):

The other file contains a bunch of value pairings, as follows (fileB):

bio types
bio defs
bio param
bio spinlock
bio buf
bootasm asm
bootasm memlayout
bootasm mmu
bootmain types
bootmain elf
bootmain x86
bootmain memlayout
cat types
cat stat
cat user

我想编写一个脚本,用文件 A 中的相应数字替换文件 B 上的值.生成新文件或改变现有文件B都没有关系.

I want to write a script that replaces the values on file B with their corresponding numbers from file A. It does not matter if it generates a new file or changes the existing file B.

有什么想法吗?谢谢

推荐答案

awk 'NR==FNR{a[$2]=$1;next}{$1=a[$1];}1' fileA fileB

NR==FNR{a[$2]=$1;next} => 当文件 A 被处理时,这是真的.形成一个关联数组,其中索引是第 2 列,第 1 列作为其值.

NR==FNR{a[$2]=$1;next} => This is true when the fileA is processed. An associative array is formed where the index is the 2nd column with the 1st column as its value.

{$1=a[$1];} => 处理第二个文件时,用数组中存储的适当值替换第一列.

{$1=a[$1];} => When the second file is processed, Replace the 1st column with the appropriate value stored in the array.

1 => 打印每一行.

1 => Print every line.

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

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