Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

linux - replace string in a file with value from another file

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

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

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.

Any ideas? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
awk 'NR==FNR{a[$2]=$1;next}{$1=a[$1];}1' fileA fileB

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];} => When the second file is processed, Replace the 1st column with the appropriate value stored in the array.

1 => Print every line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...