IT TIP

여러 줄 검색을 Perl로 대체

itqueen 2021. 1. 10. 19:42
반응형

여러 줄 검색을 Perl로 대체


나는 이런 종류의 질문이 이미 여러 번 제기되었다는 것을 알고 있습니다. 제가 다시 이곳에 온 이유는 단순하고 근본적인 것을 놓친 것 같기 때문입니다.

이러한 종류의 검색-바꾸기 루틴을 더 좋게 만들 수 있습니까? 예를 들어 같은 파일을 두 번 열지 않고. 속도 관련 조언도 환영합니다.

이것은 여러 줄 일치와 함께 작동하며 여러 줄 문자열도 대체합니다.

#!/bin/perl -w -0777

local $/ = undef;

open INFILE, $full_file_path or die "Could not open file. $!";
$string =  <INFILE>;
close INFILE;

$string =~ s/START.*STOP/$replace_string/sm;

open OUTFILE, ">", $full_file_path or die "Could not open file. $!";
print OUTFILE ($string);
close OUTFILE;

이러한 종류의 검색 및 바꾸기는 다음과 같은 한 줄로 수행 할 수 있습니다.

perl -i -pe 's/START.*STOP/replace_string/g' file_to_change

동일한 작업을 수행하는 더 많은 방법은이 스레드를 확인하십시오 . 여러 줄 검색을 처리하려면 다음 명령을 사용하십시오.

perl -i -pe 'BEGIN{undef $/;} s/START.*STOP/replace_string/smg' file_to_change

다음 코드를 one-liner에서 perl 프로그램으로 변환하려면 perlrun 문서를 참조하십시오 .

이것을 작동하는 프로그램으로 변환 할 필요가 있다면 Perl이 파일 열기 / 닫기를 처리하도록하십시오.

#!/usr/bin/perl -pi
#multi-line in place substitute - subs.pl
use strict;
use warnings;

BEGIN {undef $/;}

s/START.*STOP/replace_string/smg;

그런 다음 파일 이름을 첫 번째 인수로 사용하여 스크립트를 호출 할 수 있습니다.

$perl subs.pl file_to_change

파일 열기 / 닫기 작업을 처리 할 수있는 더 자세한 스크립트를 원하면 ( 'die'문을 모두 좋아하지는 않습니다) -i [extension] 스위치 아래에있는 perlrun의 예제를 살펴보십시오.


빠른 한 줄짜리를 찾는 모든 사람과 Perl이 명령 줄에서 RegEx 옵션을 무시하는 이유는 주석에서 짧은 대답을 가져옵니다.

perl -0pe 's/search/replace/gms' file

-0인수가 없으면 Perl은 데이터를 한 줄씩 처리 하므로 여러 검색이 실패합니다.


다음을 사용하여 파일의 전체 내용을 비웃는 것을 고려하십시오.

local $/ = undef;

open INFILE, $full_file_path or die "Could not open file. $!";
$string =  <INFILE>;
close INFILE;

And then do all the processing with $string, there's no connection between how you handle the file and how you process the contents. You'd have an issue if you opened the file for writing before you were done reading it, since opening a file for writing creates a new file, discarding the previous contents.

If all you're trying to do is save on open/close statements, then do as Jonathan Leffer suggested. If your question is about multiline search and replace, then please clarify what the problem is.


you might want to check out this Perl script, which is battle tested (used heavily in production), and has quite a lot of features, such as:

  • do multiple search-replace or query-search-replace operations
  • search-replace expressions can be given on the command line or read from a file processes multiple input files
  • recursively descend into directory and do multiple search/replace operations on all files
  • user defined perl expressions are applied to each line of each input file optionally run in paragraph mode (for multi-line search/replace)
  • interactive mode
  • batch mode
  • optionally backup files and backup numbering
  • preserve modes/owner when run as root
  • ignore symbolic links, empty files, write protected files, sockets, named pipes, and directory names
  • optionally replace lines only matching / not matching a given regular expression

https://github.com/tilo/replace_string

ReferenceURL : https://stackoverflow.com/questions/1030787/multiline-search-replace-with-perl

반응형