0

Okay so I want to add a list of strings from one file to each string from another file, example -

File1.txt (input):

asa
exe
dada
123
3456
nani
example
lol

File2.txt (input 2):

Rexample
Example

expected output.txt:

Rexampleasa
Rexampleexe
Rexampledada
Rexample123
Rexample3456
Rexamplenani
Rexampleexample
Rexamplelol
Exampleasa
Exampleexe
Exampledada
Example123
Example3456
Examplenani
Exampleexample
Examplelol
  • @EdMorton I'm new to bash so it's difficult for me to create any theoretical possibility XD sorry I know it's looked down upon to ask questions without any concept but unfortunately i can't create that. – rang runera Apr 23 '18 at 04:00
  • It's hard sometimes to know what to ask. In your case you are asking for the cartesian product of two text files. This has been asked on S.O. before and here is an answer that I think will work for you: https://stackoverflow.com/a/47675223/831878 – Ray Toal Apr 23 '18 at 04:01

1 Answers1

0

You can do that using cat and iterating over each line:

cat File2.txt | while read t2; do cat File1.txt| while read t1; do echo "${t2}${t1}"; done; done

However, depending on how many lines you have in the File2.txt this might be inefficient because you'll end up opening File1.txt many times.

With awk it might be faster:

awk 'NR==FNR { a[$0]; next } { for (i in a) print i""$0 }' File2.txt File1.txt

I'm sure there are hundreds of different ways to do it, but choosing the right one depends on the number of records you'll have in each file.

A somehow hackish but incredibly fast solution for very large data sets is:

join -j 9999 -t '' -o 1.1,2.1 File2.txt File1.txt

This last I took from @legolegs answer to How to produce cartesian product in Bash?

elyalvarado
  • 1,226
  • 8
  • 13
  • Thanks the awk version was more suitable for me! Really appreciate your help! – rang runera Apr 23 '18 at 04:24
  • @rangrunera checkout my last edit, if your dataset is really large you can use join which might be faster – elyalvarado Apr 23 '18 at 04:26
  • BTW, the `read` command is intended to parse small amounts of keyboard input, using it to parse files is generally a bad idea, unless the file is tiny. That's because it performs unbuffered reads one byte at a time, so each byte requires a system call. See https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice for further details. – PM 2Ring Apr 23 '18 at 09:17