1

I have a text file like this

word_1 root_of_word_A
word_2 root_of_word_B
word_3 root_of_word_C
word_4 root_of_word_A

And other document like this

root_of_word_A root_of_word_1
root_of_word_B root_of_word_2
root_of_word_C root_of_word_3

I have to replace in the first document with the other words of the second document, like this

word_1 root_of_word_1
word_2 root_of_word_2
word_3 root_of_word_3
word_4 root_of_word_1

I thought that I could make something like this with awk. I tried this:

awk 'NR==FNR {print $1}{c[$2]++;next};c[$1]>0{print $2}' file1 file2

The problem is that I do not know how to print the first column of the file1 and the second of the file2.

Mention that the first file and the second have different number of lines and that there is only an example to make it more clear the thing I want to do (the problem is not to convert A to 1, is the whole root_of_the_word).

3
  • do you mean if 2nd column from document should iterate when number of lines are not same on both files ?
    – Rahul
    Jun 15, 2016 at 12:48
  • Sorry, no. I trying to print in a new document the first whole file, but instead of root_of_word_A, change it for root_of_word_1. The thing is the 2 file is also very large. So I can not change it manually
    – cloudy_fog
    Jun 15, 2016 at 12:56
  • Is the second file (the root definition file) small enough to load the whole thing into memory? If so, this is a simple task for awk. This task can process the first file line by line, so it doesn't matter how large it is.
    – PM 2Ring
    Jun 15, 2016 at 13:24

2 Answers 2

2

If words in file2 are unique then you can reverse the order of the files, build an array from file2 and apply it to file1:

$ awk 'NR==FNR{a[$1]=$2;next}{print $1,a[$2]}' file2 file1
word_1 root_of_word_1
word_2 root_of_word_2
word_3 root_of_word_3
word_4 root_of_word_1
0
1

You're doing a relational join operation. There's a standard Unix command for that: join. I wish more people knew about this wonderful tool!

The join command joins two files on a common field. However, the two files need to be sorted on that field.

The common field is field 2 of the first file (file1.txt), and field 1 of the second file (file2.txt). Sort the files on these fields:

$ sort -k2,2 -o file1.txt file1.txt
$ sort -k1,1 -o file2.txt file2.txt

Then perform the join on these fields (read the manual for join), specifying that we only want to have field 1 from the first file and field 2 from the second file as outputs, and sort the result (if needed):

$ join -1 2 -2 1 -o 1.1,2.2 file1.txt file2.txt | sort
word_1 root_of_word_1
word_2 root_of_word_2
word_3 root_of_word_3
word_4 root_of_word_1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .