Perl: Find and replace specific string in multiple text file

后端 未结 6 861
甜味超标
甜味超标 2020-12-30 08:05

I need to get all the .config file in a given directory and in each of these file I need to search for a specific string and replace with another based on the file.

6条回答
  •  暖寄归人
    2020-12-30 09:01

    In case you really need to do this with perl only, which I don't recommend as there are excellent and simpler answers already posted, here goes:

    #!/usr/bin/perl
    
    # take the directory to be processed from first command line argument
    opendir($dh, $ARGV[0]);
    # take only relevant files ie. "*.config"
    @cfgs = grep { /\.config$/ } readdir($dh);
    # loop through files
    foreach(@cfgs) {
      # generate source string from the filename
      ($s) = ($_ =~ /.*_(\w+)\.config.*/);
      $s = "${s}Common";
      # generate replacement string from the filename
      $r = "~ /${s}[/ >";
      # move original file to a backup
      rename("${ARGV[0]}${_}", "${ARGV[0]}${_}.bak");
      # open backup file for reading
      open(I, "< ${ARGV[0]}${_}.bak");
      # open a new file, with original name for writing
      open(O, "> ${ARGV[0]}${_}");
      # go through the file, replacing strings
      while() { $_ =~ s/$s/$r/g; print O $_; }
      # close files
      close(I);
      close(O);
    }
    
    # end of file.
    

    Please note that doing this with simple find and or shell wildcards is much simpler. But take this as a little tutorial on how to process files with perl anyway.

提交回复
热议问题