1

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

3 Answers 3

4
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.

Sign up to request clarification or add additional context in comments.

Comments

2

This might work for you (GNU sed):

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

Comments

0

Please note the solution by @Guru doesn't work if you have undefined strings in fileB column one, for example:

fileB

...
name user
name system

will output:

...
 user
 system

The string "name" in this case will be truncated. If all rows are matched it works fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.