'CLI combining two uneven lists in two different files

I was looking for a way to combine two files that are uneven, I know there is a solution with awk but I am unable to modify it to fit my need. I.E.

File 1

a
b
c
d

File 2

1
2

Solution

a:1
b:2
c:1
d:2

if the first file is 10 words and the second is only 3 words, repeat the 3 words until the end of the first file EOF, and im sure theres a delimiter flag with ':' in there.

My best attempt was:

paste -d file1 /dev/null file2 > new_file

But that only put the 1,2 in the new list but didn't repeat.



Solution 1:[1]

For the given sample data, you may try this awk:

awk 'FNR == NR{a[++n]=$1; next} {print $1 ":" a[(FNR-1) % n + 1]}' file2 file1

a:1
b:2
c:1
d:2

Solution 2:[2]

With your shown samples, please try following awk code.

awk '
FNR==NR{
  arr[++count1]=$0
  next
}
{
  print $0":"arr[++count2]
  count2=(count2==count1?0:count2)
}
' file2 file1

Explanation: Adding detailed explanation for above code.

awk '                         ##Starting awk program from here.
FNR==NR{                      ##Checking condition FNR==NR when file2 is being read.
  arr[++count1]=$0            ##Creating arr array with index of count1(increasing it with 1) and value is current line.
  next                        ##next will skip all further statements from here.
}
{
  print $0":"arr[++count2]    ##Printing current line colon and value of arr with index of ++count2.
  count2=(count2==count1?0:count2)  ##Setting count2 to 0 if its eqal to count1 else keeping it as it is.
}
' file2 file1                 ##Mentioning Input_file names here.

Solution 3:[3]

This might work for you (GNU sed):

sed -E '1{x;s/.*/cat file2/e;x};G;s/\n/:/;P;x;s/([^\n]*)\n(.*)/\2\n\1/;x;d' file1

Prep the hold space with the contents of file2.

Append file2 to the current line, replace the first newline with : and print only the first line.

Go back to the hold space and cycle the first line.

Delete the current line(s) and repeat.

Alternative using yes and paste:

yes "$(cat file2)" | sed 'R /dev/stdin' file1 | paste -sd':\n'

or without sed:

yes "$(cat file2)" | head -$(wc -l <file1) | paste -sd':\n' file1 - 

N.B. The final - represents the contents of the cycled file2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anubhava
Solution 2 RavinderSingh13
Solution 3