よろしくお願いします.ディレクトリ内の一つのテキストファイル(joint.txt)と複数のファイルの結合を行ごとに隣へ結合するプログラムを作成しています.ここで以下のプログラムを作成したのですが,うまくいかないため,誤っている部分をご指摘願えないでしょうか.
my $dirname = '.';
opendir(DIR, $dirname) or die "$dirname: $!";
while (my $dir = readdir(DIR)) {
next unless (-f $dir);
next unless ($dir =~ /\.txt$/);
open(FILE, $dir) or die "$dir: $!";
open(FILE2,"joint.txt");
my @file = <FILE>;
my @file2 = <FILE2>;
close(FILE);
close(FILE2);
foreach my $line (@file) {
foreach my $line2 (@file2) {
chomp $line2;
$line = "$line2.",".$line";
}
}
open(NEWFILE, "> $dir") or die "$dir: $!";
print NEWFILE @file;
print NEWFILE @file2;
close(NEWFILE);
}
closedir(DIR);
No.6ベストアンサー
- 回答日時:
>>No.3
> 早速実行してみたところ,最初のファイルは思ったように処理される
> のですが,2つ目のファイル以降は処理されたファイルが前回の
> ファイルの内容を引き継ぎ,その後に出力されてしまいます.
> 具体的には以下の内容です.
結局修正してみました。
以下のような感じです。
use File::Basename;
my $dirname = '.';
die('not open : joint.txt') unless(open(FILE, 'joint.txt'));
my $file = join('', <FILE>);
close(FILE);
while(<$dirname/*.txt>) {
my $fn = (fileparse($_))[0];
next if($fn eq 'joint.txt');
my @file = split(/\n/, $file);
if(open(FILE, $_)) {
my @file2 = <FILE>;
for(my $i = 0; $i <= $#file2; $i++) {
$file[$i] .= ",$file2[$i]";
}
close(FILE);
if(open(FILE, ">$_")) {
print FILE @file;
close(FILE);
}
}
}
あと、今回の場合は関係ないのですがNo.2とNo.3で提示されたイメージ
内容が逆のような気がするのですが。(^_^;
例外的なことは殆ど考えていないので実際にはいろいろ修正する必要が
出てくると思いますけど、そこまで考慮できなくてすみません。
pick52様
ご回答ありがとうございました.実行したところ処理がうまく通りました.
pick52様には以前もご回答いただきましたね.毎度のことながら大変感謝をしております.
No.11
- 回答日時:
まだ締め切られていないようなのでぺたり。
#!/usr/bin/perl
# -*- coding: utf8 -*
use strict;
use warnings;
use Fatal qw(:void open close);
use feature ':5.10';
use File::Slurp qw/slurp read_file write_file/;
use List::MoreUtils qw/all each_array/;
my $dirname = '.';
my $joint_file = 'joint.txt';
my @files = grep {$_ !~ /$joint_file/} glob "$dirname/*.txt";
my @joint_base = slurp($joint_file);
chomp @joint_base;
foreach my $file (@files) {
my @lines = slurp($file);
my $it = each_array @joint_base, @lines;
my @newlines;
while (my @l = $it->()) {
push @newlines, join(q{,}, @l) if all {defined $_} @l;
}
write_file($file . ".new" , @newlines);
}
File::Slurp とか List::MoreUtilsがない場合用。
#!/usr/bin/perl
# -*- coding: utf8 -*
use strict;
use warnings;
use Fatal qw(:void open close);
use feature ':5.10';
sub slurp {
my $file = shift;
open my $fh, '<', $file or return;
<$fh>;
}
sub write_file {
my $file = shift;
open my $fh, '>', $file or warn "can't ooen $file";
print $fh @_;
}
my $dirname = '.';
my $joint_file = 'joint.txt';
my @files = grep {$_ !~ /$joint_file/} glob "$dirname/*.txt";
open my $fh, '<', $joint_file;
#open my $fh, '<', $joint_file; or die "could not open $joint_file by $!";
my @joint_base = <$fh>;
close $fh;
chomp @joint_base;
foreach my $file (@files) {
my @lines = slurp($file);
my @newlines;
my $min = @lines < @joint_base ? @lines : @joint_base;
foreach my $i (0 .. $min-1) {
push @newlines, join(q{,}, $joint_base[$i], $lines[$i]);
}
write_file($file . ".new" , @newlines);
}
要素数の短いものに合わせて切り詰めます・
sakusaker7様
ご回答ありがとうございます。場合分けまでしただいてありがとうございます。今は実行環境にないため、明日実行させていただきます。
そろそろ、回答を締め切りますね。
今回は、11個の回答を頂けました。大変感謝しております。
みなさん、ありがとうございました。
このような処理は多くの方がしたいと思っていると思うので、
今後はこの内容が検索で引っかかるといいと思っております。
No.8
- 回答日時:
無意味に短くしてみる試み:
open FILE, './joint.txt' or die "joint.txt: $!";
chomp(my @header = <FILE>);
close FILE;
my $dirname = '.';
opendir DIR, $dirname or die "$dirname: $!";
my @files = grep { /\.txt$/ && $_ ne 'joint.txt' } readdir DIR;
closedir(DIR);
for my $file (@files) {
open FILE, $file or dir "$file: $!";
my @lines = <FILE>;
close FILE;
open NEWFILE, ">$file" or dir "$file: $!";
print NEWFILE map {"$header[$_],$lines[$_]" } 0 .. $#lines;
close NEWFILE;
}
つなげたい 2つのファイルの行数が違うときにどうしたらいいかはしらん.
paste ってコマンドがあれば簡単なんだけどね....
Activeperl上で実行してみたところ以下のエラーがでました.
String found where operator expected at joint.pl line 11, near "dir "$file: $!"
"
(Do you need to predeclare dir?)
String found where operator expected at joint.pl line 14, near "dir "$file: $!"
"
(Do you need to predeclare dir?)
syntax error at joint.pl line 11, near "dir "$file: $!""
syntax error at joint.pl line 14, near "dir "$file: $!""
Execution of joint.pl aborted due to compilation errors.
兎にも角にもありがとうございました.
No.7
- 回答日時:
如何でしょうか。
----------------
my $dirname = './';
my $filename = './joint.txt';
open my $file, $filename or die "$filename: $!\n";
my @content = <$file>;
close $file;
chomp @content;
while (my $line = <$dirname*.txt>) {
next if $line eq $filename;
open my $file, $line or die "$line: $!\n";
my @try = <$file>;
close $file;
chomp @try;
open my $newfile, '>', $line or die "$line: $!\n";
for (my $i = 0; $i < @content; $i ++) {
last unless defined $try[$i];
print $newfile "$content[$i],$try[$i]\n";
}
close $newfile;
}
No.3
- 回答日時:
use File::Basename;
my $dirname = '.';
die('not open : joint.txt') unless(open(FILE, 'joint.txt'));
my @file = <FILE>;
close(FILE);
while(<$dirname/*.txt>) {
my $fn = (fileparse($_))[0];
next if($fn eq 'joint.txt');
if(open(FILE, $_)) {
my @file2 = <FILE>;
for(my $i = 0; $i <= $#file2; $i++) {
chomp($file[$i]);
$file[$i] .= ",$file2[$i]";
}
close(FILE);
print @file;
if(open(FILE, ">$_")) {
print FILE @file;
close(FILE);
}
}
}
こんな感じでどうでしょうか。
ファイルが開けなかったときのエラー処理まではしていませんけど。
この回答への補足
pick52様
ご回答ありがとうございます.先日はお世話になりました.
早速実行してみたところ,最初のファイルは思ったように処理されるのですが,2つ目のファイル以降は処理されたファイルが前回のファイルの内容を引き継ぎ,その後に出力されてしまいます.具体的には以下の内容です.
joint.txt
-------------------
a
b
c
d
e
1.txt
----------------------
a,1
b,2
c,3
d,4
e,5
2.txt
----------------------
a,1a,1
b,2b,2
c,3c,3
d,4d,4
e,5e,5
たびたび申し訳ありませんが,なにとぞよろしくお願いします.
お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!
似たような質問が見つかりました
- UNIX・Linux 実行の仕方及び実行結果が分かりません。 2 2022/11/17 19:31
- Visual Basic(VBA) ExcelVBAに関する質問 3 2023/02/17 10:47
- CGI htmlからパラメータで、cgiに渡したい。 1 2023/02/06 16:15
- Excel(エクセル) Excelにて、フォルダ内のTextファイルをマクロで統合すると文字化けしてしまう時の解消コード 4 2023/01/01 07:32
- PHP imageフォルダに、画像をリサイズして保存する時のファイル名を変更したい 1 2023/05/30 11:39
- Ruby 教えてください 2 2023/01/04 17:50
- Perl perlのflock関数でロックをかけたままopen関数で何度もファイルを開きなおすことはできますか 3 2023/05/01 22:25
- パチンコ・スロット パチンコ屋 フィーバー池袋西口店 の換金所の場所どこか教えて下さい https://www.p-wo 1 2022/06/09 18:01
- その他(プログラミング・Web制作) python flask から fastapiへの移行時のエラー対処 1 2023/02/05 12:26
- Visual Basic(VBA) このVBAでExcelアプリケーションを作成は必要ですか? 3 2023/07/19 21:13
関連するカテゴリからQ&Aを探す
おすすめ情報
デイリーランキングこのカテゴリの人気デイリーQ&Aランキング
-
一つのテキストファイルと複数...
-
window.open でのファイル指定方法
-
フォルダ内のファイルを全て開...
-
並び方、
-
PerlでのUseless use...
-
python renameについて
-
Perlの質問:行と列を入れ替え...
-
ExcelをCSV書き出す場合のシー...
-
サーバーにある特定の拡張子フ...
-
batファイルでrenameができませ...
-
エクセルVBA コードが同じでも...
-
VBAでCSVファイルを途中行まで...
-
パスから最後のディレクトリだ...
-
VBAで巨大なファイルの途中から...
-
配列の中に重複文字列があるか...
-
VBAでCSVファイルの特定行を書...
-
2つのCSVファイルをマッチング
-
perlにて2つのファイル比較
-
openした後、closeしないでプロ...
-
エクセルVBAで素数だけを出力す...
マンスリーランキングこのカテゴリの人気マンスリーQ&Aランキング
-
python renameについて
-
fgets で値が取得できない
-
window.open でのファイル指定方法
-
巨大なテキストの最終行を取得...
-
ファイル全てを .xlsm に変更し...
-
read() on unopened filehandle...
-
csvファイルの横方向への改行に...
-
VBAコードを張り付け後のエクセ...
-
Firefox で file:// で始まる U...
-
JSP URLに表示される拡張子 .jsp
-
drtファイルはどうしたら開...
-
並び方、
-
重複ファイル名ある場合ファイ...
-
VBA テキストファイルを読み取...
-
cgiでサーバーにファイルを追加...
-
HTMLのフォームで画像と文...
-
WindowsでPerlをする際,1行目の...
-
バイナリファイルの出力
-
Perlでのパーミッション変更の仕方
-
foreach内での変数の扱い?
おすすめ情報