S
S
Starik0072019-03-18 13:38:16
Perl
Starik007, 2019-03-18 13:38:16

How to search between certain words before replacing?

I have an apache2.conf file and I'm trying to make a replacement in the line "ScriptAlias ​​/php-bin/ /var/www/*" , only after doing a search between the ServerName values ​​$domain and < / VirtualHost >.
Can you please tell me how can this be implemented?
Now I'm learning about perl, I found an example with a replacement, but it completely erases everything found between ServerName and < / VirtualHost > , and I need to at least add, and ideally replace the line within ServerName $domain and < / VirtualHost >.

my $apacheconf = '/etc/apache2/apache2.conf';
    open(my $fh, '<:encoding(UTF-8)', $apacheconf);	
  
    my $newtext = "\n\tScriptAlias /php-bin/ /var/www/"."$user"."\n";

    my $find = "/var/www/$user/data/www/$domain";
    
    my $str = "";

    while (my $rowa = <$fh>) {
      chomp $rowa;
      $str .= "$rowa\n";
    }
    close $fh;
    my $string = $str;
    $string =~ s/(ServerName $domain).*?(\<\/VirtualHost\>)/$1$newtext$2/gis;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
ShamblerR, 2019-03-18
@ShamblerR

give an example of a real config

A
Alexander Sapozhnikov, 2019-06-07
@shoorick

1. First, read the documentation - man perlre - useful in any case.
2. Then decide on the quantifiers in the regular expression: the asterisk with a question mark confuses me - usually, in order to indicate zero or more of any characters, either an asterisk is used if greedy behavior is needed ( .*- the maximum possible number of any characters) or plus with a question mark, if greed is not needed ( .+?is the minimum possible number of any characters).
3. Along the way, you can also simplify the procedure for reading a file - you can immediately read it into one long line, and not collect it piece by piece.
4. As a further development of the third point, it is worth using more actively the various keys with which the pearl interpreter is launched in order not to write any routine code by hand - see man perlrun . For example, a multi-line inplace-replacement in a file with a backup can be done with the command

perl -0777 -pi~ -e 's/что/куда/g' /путь/к/файлу/где/менять.conf

That is, instead of a heap of incomprehensible garbage code, in essence, there will be only one replacement operator - nothing more.
5. Well, you still need to clearly articulate what you need. I can assume that you want to replace the string "/var/www/$user/data/www/$domain"with "\n\tScriptAlias /php-bin/ /var/www/$user\n", but your question doesn't seem to suggest that.
6. In your example, too much is erased due to the fact that you change to new content not what is in the variable $find, but anything at all ( .*).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question