Perlでgzipファイルの入出力(Compress::Zlibの利用)
- Tue
- 22:09
- perl
Perlのgzipファイル入出力のサンプル。
gzipとzipはちょっと異なっていますが、今回はアーカイバでない方のgzipを。
実際にはtarと併用して、「tar -zcvf」でdir丸ごと圧縮、「tar -zxvf」で展開(-Cで展開先を指定)を使うことが多いですが。
そんなこんなで今回は、Compress::Zlib (CPAN) と FileHandle (CPAN) の2つのCPANライブラリを利用。
使えるものは何でも使っていきましょう。
と、いうことでサンプルの作成。
gzip.pl
in.csv
実行結果
また、FileHandleを使った例は下記に。
gzipとzipはちょっと異なっていますが、今回はアーカイバでない方のgzipを。
実際にはtarと併用して、「tar -zcvf」でdir丸ごと圧縮、「tar -zxvf」で展開(-Cで展開先を指定)を使うことが多いですが。
そんなこんなで今回は、Compress::Zlib (CPAN) と FileHandle (CPAN) の2つのCPANライブラリを利用。
使えるものは何でも使っていきましょう。
と、いうことでサンプルの作成。
gzip.pl
01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: | #!/usr/local/bin/perl use Compress::Zlib; use FileHandle; my $prm_in_file = $ARGV[0]; my $prm_ot_file = $ARGV[1]; my $in_gz = gzopen($prm_in_file, 'rb') or die "*** file open error. file='$prm_in_file' $!"; my $ot_gz = gzopen($prm_ot_file, 'wb') or die "*** file open error. file='$prm_ot_file' $!"; $cnt = 1; $ot_gz->gzwrite("$cnt:first line\n"); while(($read_size = $in_gz->gzreadline($in_buf)) > 0) { die($in_gz->gzerror) if ($read_size < 0); chomp($in_buf); $cnt++; $ot_gz->gzwrite("$cnt:$in_buf\n"); } $cnt++; $ot_gz->gzwrite("$cnt:end line\n"); $in_gz->gzclose(); $ot_gz->gzclose(); |
in.csv
$ file gzip_in.txt.gz gzip_in.txt.gz: gzip compressed data, was "gzip_in.txt", from Unix, last modified: Tue Mar 31 07:46:37 2015 $ zcat gzip_in.txt.gz aaa bbb cccgzip_in.txt.gzを入力して、行番号、ヘッダーレコード、トレーラーレコードを追加してgzip_ot.txt.gzファイルに出力。
実行結果
$ ./gzip.pl gzip_in.txt.gz gzip_ot.txt.gz $ file gzip_ot.txt.gz gzip_ot.txt.gz: gzip compressed data, from Unix, last modified: Tue Mar 31 07:59:26 2015 $ zcat gzip_ot.txt.gz 1:first line 2:aaa 3:bbb 4:ccc 5:end line
また、FileHandleを使った例は下記に。
gzip2.pl
01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: | #!/usr/local/bin/perl use Compress::Zlib; use FileHandle; my $prm_in_file = $ARGV[0]; my $prm_ot_file = $ARGV[1]; my $in_gz = gzopen($prm_in_file, 'rb') or die "*** file open error. file='$prm_in_file' $!"; my $ot_gz = FileHandle->new("| gzip -c > $prm_ot_file") or die "*** file open error. file='$prm_ot_file' $!"; $cnt = 1; print $ot_gz "$cnt:first line\n"; while(($read_size = $in_gz->gzreadline($in_buf)) > 0) { die($in_gz->gzerror) if ($read_size < 0); chomp($in_buf); $cnt++; print $ot_gz "$cnt:$in_buf\n"; } $cnt++; print $ot_gz "$cnt:end line\n"; $in_gz->gzclose(); $ot_gz->close(); |
- 関連記事
-
- PerでJSON その2(JSONとJSON::XS)
- PerでJSON (JSON::XS)
- Perlでgzipファイルの入出力(Compress::Zlibの利用)
- PerlでCSVファイルの入出力(Text::CSV_XSの利用)
- perlのGetopt::Long(GetOptions)によるプログラム引数(パラメータ)の取得
Comment
Trackback
- URL
- https://nosource.blog.fc2.com/tb.php/123-839f24b5
- この記事にトラックバック(FC2Blog User)