Perlで特定の行を削除する方法:実践サンプルコード付き

Perlを使用して、特定の行を削除する方法は、ファイルを読み込んで不要な行を新しいファイルに書き込むことができます。以下は、特定の文字列を含む行を削除する方法を示すサンプルコードです。

use strict;
use warnings;

my $input_file = 'input.txt';
my $output_file = 'output.txt';
my $string_to_delete = 'delete this line';

open(my $input_fh, '<', $input_file) or die "Cannot open $input_file: $!";
open(my $output_fh, '>', $output_file) or die "Cannot open $output_file: $!";

while (my $line = <$input_fh>) {
    if ($line !~ /$string_to_delete/) {
        print $output_fh $line;
    }
}

close($input_fh);
close($output_fh);

# Rename the output file to the original file
rename $output_file, $input_file or die "Cannot rename $output_file to $input_file: $!";

この例では、まず、入力ファイルinput.txt、出力ファイルoutput.txt、および削除する文字列delete this lineを定義します。その後、入力ファイルと出力ファイルを開き、入力ファイルの各行を走査します。削除する文字列が含まれていない行は、出力ファイルに書き込まれます。最後に、ファイルハンドルを閉じ、出力ファイルを元の入力ファイル名にリネームして、特定の行を削除する操作が完了します。

bannerAds