1

For Example: I have two files

input.txt

one
two
three
four
five

output.txt

1
2
3
4
5

I want to merge these two files and to get another output file (e.g, match.txt) like this,

one 1
two 2
three 3
...

Moreover, when I shuffle these two .txt files randomly, the output file (match.txt) will also merge the correct data like that...

three 3
two 2
five 5
...

How can I write shell script?

  • You need to be clear if the numbers are examples, or specific. Do you always want the word one to be following by the number 1, and in the output file, the order is based on the words? Or are they examples of other possible values in some way, in which case, it needs more detail. – EightBitTony Oct 31 '17 at 15:23
5

Simply with paste command:

paste -d' ' input.txt output.txt > match.txt

The match.txt content:

one 1
two 2
three 3
four 4
five 5

With shuffling (via sort command):

paste -d' ' input.txt output.txt | sort -R

An exemplary output:

two 2
four 4
one 1
three 3
five 5
  • I don't think that this is what the OP describes. Shuffle file 1, then shuffle file2 and at the end match the two suffled files together but in the correct logical way like two 2. Is a nice exercise. – George Vasiliou Oct 31 '17 at 20:25
  • @GeorgeVasiliou, It's obvious that that scheme that you described requires a predefined "mapping" of logical pairs {"one": 1, "two": 2, ...}. That's not the case. And what if the input list contains the items from one to ninety? What would be your answer for such nice exercise? – RomanPerekhrest Oct 31 '17 at 21:09
  • I fully agree. Even my answer is based in a predifined mapping. I can not think any other "programming" way to match one with 1. Sorry, i didn't want to be frustrating - it just sounded a nice exercise to match one with 1 – George Vasiliou Nov 1 '17 at 10:14
  • @GeorgeVasiliou, that's ok – RomanPerekhrest Nov 1 '17 at 10:15
0
$ cat input.txt
five
one
three
two
four

$ awk 'BEGIN{a["one"]=1;a["two"]=2;a["three"]=3;a["four"]=4;a["five"]=5}$0 in a{print $0,a[$0]}' input.txt
five 5
one 1
three 3
two 2
four 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.