Replace a line in a file with a value from another file

I have two files. One of them defines a set of pairs of numerical values ​​as follows ( fileA ):

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

Another file contains a bunch of values, as shown below ( 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 

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

Any ideas? Thanks

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

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

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

1 => Print each line.

+3
source

This may work for you (GNU sed):

 sed 's|^\s*\(\S*\)\s*\(.*\)$|/^\2\\>/s//\1/|' fileA | sed -f - fileB 
+1
source

Source: https://habr.com/ru/post/1201392/


All Articles