Pregunta

My two input files are as follows:

new

111
222
333

old

555
666

I want to merge them to get the following output

111
555
222
666
333

This is what I've tried so far

i=1
while read line
do
   head -$i $1 | tail -1
   head -$i $2 | tail -1 
   i=$(($i+1));
done < $1

This is the output I receive

111
555
222
666
333
666

How do I prevent it from taking the last line in 'old' twice? It should also be able to merge the two files if the second file is larger than the first.

¿Fue útil?

Solución

You should just use paste:

paste -d"\n" /tmp/file1 /tmp/file2

Otros consejos

In case the OP actually wanted to do head and tail just for experimentation, here's a modification of his code:

lenA=`wc -l $1 | awk '{print $1}'`
lenB=`wc -l $2 | awk '{print $1}'`

i=1
while read line
do
   tail -$(($lenA - $i + 1 >= 0?$lenA - $i + 1:0)) $1 | head -1
   tail -$(($lenB - $i + 1 >= 0?$lenB - $i + 1:0)) $2 | head -1
   i=$(($i+1));
done < $1

Here is a way using bash only:

while true; do    
    read -r newline
    read -r oldline <&3
    if [[ -z "$newline" && -z "$oldline" ]]; then 
        break;
    fi
    if [[ ! -z "$newline" ]]; then 
        echo "$newline"
    fi
    if [[ ! -z "$oldline" ]]; then
        echo "$oldline"
    fi
done <new 3<old

Output:

111
555
222
666
333

You could use a BASH read loop on one file and pass the increment variable to awk to get the same line number from the other file so you can print them in the order you want.

#!/bin/bash

i=1
while read line; do
    echo $line
    awk -v i=$i 'NR==i' $2
    ((i++))
done < $1
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top