kedi dosyası1
foo
ice
two
kedi dosyası2
bar
cream
hundred
İstenen çıktı:
foobar
icecream
twohundred
dosya1 ve dosya2, işleri kolaylaştırırsa, senaryoda her zaman aynı miktarda satır olacaktır.
kedi dosyası1
foo
ice
two
kedi dosyası2
bar
cream
hundred
İstenen çıktı:
foobar
icecream
twohundred
dosya1 ve dosya2, işleri kolaylaştırırsa, senaryoda her zaman aynı miktarda satır olacaktır.
Bu iş için doğru araç muhtemelen paste
paste -d '' file1 file2
Ayrıntılar için man paste
bölümüne bakın.
awk yolundaki soruları gösterir:
awk '{getline x<"file2"; print %pre%x}' file1
getline x<"file2"
, satırın tamamını file2 üzerinden okur ve x değişkenine geçer. print x
x
, %code% 'yi ve file2 kaydedilmiş satırı olan %code% ' yi kullanarak dosya1 satırını tüm satırdan yazdırır. paste
gitmenin yoludur . Diğer bazı yöntemleri kontrol etmek isterseniz, python
çözümdür:
#!/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()
Birkaç satırınız varsa:
#!/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)))
Eşit olmayan sayıda satır için, bunun önce sonlanan dosyanın son satırında biteceğini unutmayın.
Ayrıca, bash
pure ile (bunun boş satırları tamamen yok sayacağına dikkat edin):
#!/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
Perl yolu, anlaşılması kolay:
#!/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";
}
Şununla başla:
./merge file1 file2
Çıktı:
foobar
icecream
twohundred
Etiketlerdeki diğer soruları oku bash sed text-processing perl awk