-2

リストを含むファイルがあります。それを呼び出しますtbl.lst

a
b
c
d
e

項目を括弧で囲み、コンマで区切った出力ファイルを作成したいと考えています。誰かが Perl でこれを行う方法を教えてもらえますか?

期待される出力:

MYTABLES=(a,b,c,d,e)
4

3 に答える 3

3
perl -lne 'push @A, $_; END { print "MYTABLES=(", join(",", @A), ")";}' tbl.lst

入力ファイルが与えられた場合tbl.lst:

a
b
c
d
e

出力は次のとおりです。

MYTABLES=(a,b,c,d,e)

Perl スクリプトのすべてのスペースはオプションです (ただし、スペースの方がわかりやすいでしょう)。

于 2013-09-17T05:40:07.903 に答える
1

このスクリプトはフィルターとして機能します。ファイルを読み取り、次のように結果を stdout に出力します。

./script file

どうぞ:

#!/usr/bin/perl
while (<>) {
    s/\r|\n//g;  # On any platform, strip linefeeds on any (other) platform
    push @items, $_
}
print "MYTABLES=(";
while (@items) {
    $item = shift @items;
    print $item;
    print @items ? "," : ")\n";
}

入力ファイルが非常に大きくなる場合は、リストに読み込むことを避け、代わりに行ごとに厳密に作業することをお勧めします。次に、アイテムの前にセパレーターを印刷するのがコツです。

print "MYTABLES=";
while (<>) {
    print $first_printed ? "," : "(";
    s/\r|\n//g;  # On any platform, strip linefeeds on any (other) platform
    print;
    $first_printed = 1; 
}
print ")\n";
于 2013-09-17T05:27:27.797 に答える
0
awk 'NR!=1{a=a","}{a=a$0}END{print "MYTABLES=("substr(a,0,length(a))")"}' your_file >output.txt

以下でテスト:

> cat temp
a
b
c
d
e
> awk 'NR!=1{a=a","}{a=a$0}END{print "MYTABLES=("substr(a,0,length(a))")"}' temp
MYTABLES=(a,b,c,d,e)
于 2013-09-17T05:41:25.507 に答える