cat file1
foo
ice
two
cat file2
bar
cream
hundred
Output desiderato:
foobar
icecream
twohundred
file1 e file2 avranno sempre la stessa quantità di linee nel mio scenario, nel caso in cui ciò faciliti le cose.
cat file1
foo
ice
two
cat file2
bar
cream
hundred
Output desiderato:
foobar
icecream
twohundred
file1 e file2 avranno sempre la stessa quantità di linee nel mio scenario, nel caso in cui ciò faciliti le cose.
Lo strumento giusto per questo lavoro è probabilmente paste
paste -d '' file1 file2
Vedi man paste
per i dettagli.
Tramite le awk modo:
awk '{getline x<"file2"; print $0x}' file1
getline x<"file2"
legge l'intera riga da file2 e contiene la variabile x . print $0x
stampa l'intera riga da file1 utilizzando $0
poi x
che è la riga salvata di file2 . paste
è la strada da percorrere . Se vuoi controllare altri metodi, ecco una soluzione python
:
#!/usr/bin/env python2
import itertools
with open('/path/to/file1') as f1, open('/path/to/file2') as f2:
lines = itertools.izip_longest(f1, f2)
for a, b in lines:
if a and b:
print a.rstrip() + b.rstrip()
else:
if a:
print a.rstrip()
else:
print b.rstrip()
Se hai un numero limitato di righe:
#!/usr/bin/env python2
with open('/path/to/file1') as f1, open('/path/to/file2') as f2:
print '\n'.join((a.rstrip() + b.rstrip() for a, b in zip(f1, f2)))
Tieni presente che per un numero non uguale di righe, questo termina con l'ultima riga del file che termina per prima.
Inoltre, con% bash
(nota che questo ignorerà totalmente le righe vuote):
#!/bin/bash
IFS=$'\n' GLOBIGNORE='*'
f1=($(< file1))
f2=($(< file2))
i=0
while [ "${f1[${i}]}" ] && [ "${f2[${i}]}" ]
do
echo "${f1[${i}]}${f2[${i}]}" >> out
((i++))
done
while [ "${f1[${i}]}" ]
do
echo "${f1[${i}]}" >> out
((i++))
done
while [ "${f2[${i}]}" ]
do
echo "${f2[${i}]}" >> out
((i++))
done
Il modo perl, facile da capire:
#!/usr/bin/perl
$filename1=$ARGV[0];
$filename2=$ARGV[1];
open(my $fh1, "<", $filename1) or die "cannot open < $filename1: $!";
open(my $fh2, "<", $filename2) or die "cannot open < $filename2: $!";
my @array1;
my @array2;
while (my $line = <$fh1>) {
chomp $line;
push @array1, $line;
}
while (my $line = <$fh2>) {
chomp $line;
push @array2, $line;
}
for my $i (0 .. $#array1) {
print @array1[$i][email protected][$i]."\n";
}
Inizia con:
./merge file1 file2
Output:
foobar
icecream
twohundred
Leggi altre domande sui tag bash sed text-processing perl awk