用 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;
75258 次浏览

This kind of search and replace can be accomplished with a one-liner such as -

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

For more ways to accomplish the same thing check out this thread. To handle multi-line searches use the following command -

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

In order to convert the following code from a one-liner to a perl program have a look at the perlrun documentation.

If you really find the need to convert this into a working program then just let Perl handle the file opening/closing for you.

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


BEGIN {undef $/;}


s/START.*STOP/replace_string/smg;

You can then call the script with the filename as the first argument

$perl subs.pl file_to_change

If you want a more meatier script where you get to handle the file open/close operations(don't we love all those 'die' statements) then have a look at the example in perlrun under the -i[extension] switch.

Considering that you slurp in the whole contents of the file with:

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.

Pulling the short answer from the comments, for anyone looking for a quick one-liner, and the reason Perl is ignoring their RegEx options from the command line.

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

Without the -0 argument, Perl processes data line-by-line, which causes multiline searches to fail.

you might want to check out my 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

the combination of bash script + perl -pi -e is unbeatable - an example of bash function to directly type the search and replace strings before the EOF label :

# usage put into foobar.sh file, source foobar.sh file
# call directly into the shell do_multiline_srch_and_replace
do_multiline_srch_and_replace(){


test -z $dir_to_work && {
echo "You must export dir_to_work=<<the-dir>> - it is empty !!!"; exit 1;
}
test -d $dir_to_work || {
echo "The dir to work on: \"$dir_to_work\" is not a dir !!!"; exit 1;
}


echo "INFO dir_to_work: $dir_to_work" ; sleep 1
echo "INFO START :: searching and replacing in the non-binary files only"


while read -r file ; do (
echo "DEBUG working on the following file: $file"


# those pattern in the file names we want to skip usually - git, not , py files
case "$file" in
*.git*)
continue ;;
*node_modules*)
continue ;;
*.venv*)
continue ;;
esac
# note the string should be exactly between the s|| and the replace str between the ||gs
# the 'EOF' guarantees that no special chars from the shell will affect the result
perl -pi - <<'EOF' "$file"
BEGIN{undef $/;}
s|a multiline
string|the multiline
string to replace|gs
EOF
);
done < <(find $dir_to_work -type f -not -exec file {} \; | grep text | cut -d: -f1)


echo "INFO STOP  :: search and replace in non-binary files"


}