drstar drstar -4 years ago 117
Linux Question

replace every word in a file with the value from another dictionary file

I have a text file mytext.txt, each line of the text is a sentence:

the quick brown fox jumps over the lazy dog
colorless green ideas sleep furiously


Then I have a dictionary file dict.txt like this:

the: A
quick: B
brown: C
fox: D
jumps: E
over: F
lazy: G
dog: H
colorless: I
green: J
ideas: K
sleep: L
furiously: M


I want to replace each word in mytext.txt with the value in dict.txt, like this:

A B C D E F A G H
I J K L M


How can I do it using awk or sed?

Answer Source
$ awk -F'[: ]' 'FNR==NR{a[$1]=$NF;next}{for(i in a)gsub(i,a[i])}1' dist mytext

OR

$ awk -F'[: ]' 'FNR==NR{ a[$1]=$NF; next }
  { for(i=1;i<=NF;i++) if($i in a)$i=a[$i] }1' dist mytext

Input

$ cat mytext 
the quick brown fox jumps over the lazy dog
colorless green ideas sleep furiously

$ cat dist 
the: A
quick: B
brown: C
fox: D
jumps: E
over: F
lazy: G
dog: H
colorless: I
green: J
ideas: K
sleep: L
furiously: M

Output

$ awk -F'[: ]' 'FNR==NR{a[$1]=$NF;next}{for(i in a)gsub(i,a[i])}1' dist mytext 
A B C D E F A G H
I J K L M

$ awk -F'[: ]' 'FNR==NR{a[$1]=$NF; next}
{ for(i=1; i<=NF;i++) if($i in a)$i=a[$i] }1' dist mytext 
A B C D E F A G H
I J K L M
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download