Perl単行編集テクニック

3067 ワード

Perlには簡単な単行テクニックがあり、ファイル編集の検索を簡単に実現できます.一般的な方法をいくつか紹介します.
C:\>perl -h

Usage: D:\Perl\bin\perl.exe [switches] [--] [programfile] [arguments]
  -0[octal]         specify record separator (\0, if no argument)
  -a                autosplit mode with -n or -p (splits $_ into @F)
  -C[number/list]   enables the listed Unicode features
  -c                check syntax only (runs BEGIN and CHECK blocks)
  -d[:debugger]     run program under debugger
  -D[number/list]   set debugging flags (argument is a bit mask or alphabets)
  -e program        one line of program (several -e's allowed, omit programfile)
  -E program        like -e, but enables all optional features
  -f                don't do $sitelib/sitecustomize.pl at startup
  -F/pattern/       split() pattern for -a switch (//'s are optional)
  -i[extension]     edit <> files in place (makes backup if extension supplied)
  -Idirectory       specify @INC/#include directory (several -I's allowed)
  -l[octal]         enable line ending processing, specifies line terminator
  -[mM][-]module    execute "use/no module..." before executing program
  -n                assume "while (<>) { ... }" loop around program
  -p                assume loop like -n but print line also, like sed
  -P                run program through C preprocessor before compilation
  -s                enable rudimentary parsing for switches after programfile
  -S                look for programfile using PATH environment variable
  -t                enable tainting warnings
  -T                enable tainting checks
  -u                dump core after parsing program
  -U                allow unsafe operations
  -v                print version, subversion (includes VERY IMPORTANT perl info)
  -V[:variable]     print configuration summary (or a single Config.pm variable)
  -w                enable many useful warnings (RECOMMENDED)
  -W                enable all warnings
  -x[directory]     strip off text before #!perl line and perhaps cd to directory
  -X                disable all warnings

perl -ne 'scirpt' filename
ファイルをループして読み込み、スクリプトに基づいて各行を処理
perl -pe 'scirpt' filename
ファイルをループして読み込み、スクリプトに基づいて各行を処理します.印刷処理後の各行の内容は異なります.
perl -i.bak -pe 's/string1/string2/g' filename
ファイルの各行の文字列string 1を置き換え、元のファイルをバックアップします.bak.なお、置換にはパラメータpを使用する必要があります
perl -ne 'print if 1..10' filename
ファイルの最初の10行の処理に対して、行数は1から計算します
perl -ne 'print if/START/../END/' filename
ファイル内容については、START行を含めて印刷を開始し、END行を含めて終了します.このような段落が複数含まれている場合は、すべて印刷され、行にENDが含まれていない場合は、ファイルの終了まで印刷されます.
最後に実際の実行中のコードを見てみましょう
D:\Tmp>perl -MO=Deparse -ne "print if 1..10" test.pl
LINE: while (defined($_ = <ARGV>)) {
    print $_ if 1 .. 10;
}
-e syntax OK

D:\Tmp>perl -MO=Deparse -pe "print if 1..10" test.pl
LINE: while (defined($_ = <ARGV>)) {
    print $_ if 1 .. 10;
}
continue {
    print $_;
}
-e syntax OK