2010-02-08 85 views
1

我輸入這樣串聯多條線路與鑑別

輸入:

a,b,c 
d,e,f 
g,h,i 
k,l,m 
n,o,p 
q,r,s 

我婉能夠與像鑑別來串聯線「|」

輸出:

a,b,c|d,e,f|g,h,i 
k,l,m|n,o.p|q,r,s 

的文件有100萬行,我希望能夠之前來連接,如示例行。

有關如何解決此問題的任何想法?

+1

你想連接成3個這樣的組,或者你想連接成1大行嗎? – Pace 2010-02-08 03:54:45

回答

2

@OP,如果你想將它們分組,每3條記錄,

$ awk 'ORS=(NR%3==0)?"\n":"|"' file 
a,b,c|d,e,f|g,h,i 
k,l,m|n,o,p|q,r,s 

用Perl,

$ perl -lne 'print $_ if $\ = ($. % 3 == 0) ? "\n" : "|"' file 
a,b,c|d,e,f|g,h,i 
k,l,m|n,o,p|q,r,s 
+0

正義的awk福。如果只有2行,那麼+1 – 2010-02-08 04:41:43

0

GAWK:

BEGIN { 
    state=0 
} 

state==0 { 
    line=$0 
    state=1 
    next 
} 

state==1 { 
    line=line "|" $0 
    state=2 
    next 
} 

state==2 { 
    print line "|" $0 
    state=0 
    next 
} 
0

如果Perl是很好,你可以試試:

$i = 1; 
while(<>) { 
     chomp; 
     unless($i % 3) 
     { print "$line\n"; $i = 1; $line = "";} 
     $line .= "$_|"; 
     $i++; 
} 

運行:

perl perlfile.pl 1millionlinesfile.txt 
0
$ paste -sd'|' input | sed -re 's/([^|]+\|[^|]+\|[^|]+)\|/\1\n/g'

隨着paste,我們的線路連接在一起,然後sed切丁起來。該模式抓取3個管道終止字段的運行並用換行符替換它們各自的最終管道。

用Perl:

#! /usr/bin/perl -ln 

push @a => $_; 
if (@a == 3) { 
    print join "|" => @a; 
    @a =(); 
} 

END { print join "|" => @a if @a } 
+0

不說它會發生,但是,如果OP的數據包含「|」本身?那麼sed正則表達式會搞亂。 – ghostdog74 2010-02-08 04:43:55

2

由於您的代碼包含sed這裏有一個使用它的方法:

sed 'N;N;s/\n/|/g' datafile 
+0

會出現問題嗎? – 2010-02-08 05:07:37

+0

我不確定我是否理解,但如果你的意思是你希望結果是每兩行(而不是三個)合併成一個,所以你得到「a,b,c | d,e,f」使用一個這樣的「N」:'sed'N; s/\ n/|/g'datafile' – 2010-02-08 05:41:10

+0

@Dyno,如果OP想要連續每3行,並且他的文件中只有2行,沒有效果。 (如果OP仍然想用「|」連接這兩行) – ghostdog74 2010-02-08 05:52:42