小编典典

用另一个文件中的值替换文件中的字符串

linux

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

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

另一个文件包含一堆值配对,如下所示( 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都没有关系。

有任何想法吗?谢谢


阅读 308

收藏
2020-06-07

共1个答案

小编典典

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

NR == FNR {a [$ 2] = $ 1; next} =>处理fileA时为true。形成一个关联数组,其中索引是第二列,第一列为其值。

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

1 =>打印每一行。

2020-06-07