2

This question already has an answer here:

I have two files with the same number of words and column fields in each line. I want to append these two files word by word. For example:

File 1:

A1 B1 C1
D1 E1 B1 C1

File 2:

A2 B2 C2
D2 E2 B2 C2

The output should be (the number of words should be respected):

A1_A2 B1_B2 C1_C2 
D1_D2 E1_E2 B1_B2 C1_C2

marked as duplicate by Mat, Community Jul 14 '16 at 9:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Is blank line between lines intended? – cuonglm Jul 14 '16 at 8:14
  • No No.. it is here for formatting. sorry. I have no blank lines. – user3397178 Jul 14 '16 at 8:15
5

The awk solution:

awk '{
    getline a <"file2"
    split(a,A)
    for(i=1;i<=NF;i++)
        printf("%s_%s ", $i, A[i])
    print ""
    }' file1

paste + sed:

paste file1 file2 | 
sed '
    :a
    s/\(\(^\|\s\)[^_[:blank:]]\+\b\)\s*\(.*\t\)\(\S\+\)\s*/\1_\4 \3/
    ta
    s/\s*$//
    '

bash loop:

exec 3<file1 4<file2
while read -u 3 a ; read -u 4 b 
do 
    echo $(paste -d_ <(printf '%s\n' $a) <(printf '%s\n' $b))
done

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