Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic Perl find and replace using grep inside backticks
    primarykey
    data
    text
    <p>I am trying to do a dynamic search and replace with Perl on the command line with part of the replacement text being the output of a grep command within backticks. Is this possible to do on the command line, or will I need to write a script to do this?</p> <p>Here is the command that I thought would do the trick. I thought that Perl would treat the backticks as a command substitution, but instead it just treats the backticks and the content within them as a string:</p> <pre><code>perl -p -i -e 's/example.xml/http:\/\/exampleURL.net\/`grep -ril "example_needle" *`\/example\/path/g' `grep -ril "example_needle" *` </code></pre> <p>UPDATE:</p> <p>Thanks for the helpful answers. Yes, there was a typo in my original one-liner: the target file of grep is supposed to be *.</p> <p>I wrote a small script based on Schewrn's example, but am having confusing results. Here is the script I wrote:</p> <pre><code> #!/usr/bin/env perl -p -i my $URL_First = "http://examplesite.net/some/path/"; my $URL_Last = "/example/example.xml"; my @files = `grep -ril $URL_Last .`; chomp @files; foreach my $val (@files) { @dir_names = split('/',$val); if(@dir_names[1] ne $0) { my $url = $URL_First . @dir_names[1] . $URL_Last; open INPUT, "+&lt;$val" or die $!; seek INPUT,0,0; while(&lt;INPUT&gt;) { $_ =~ s{\Q$URL_Last}{$url}g; print INPUT $_; } close INPUT; } } </code></pre> <p>Basically what I am trying to do is:</p> <ol> <li>Find files that contain $URL_Last.</li> <li>Replace $URL_Last with $URL_First plus the name of the directory that the matched file is in, plus $URL_Last.</li> <li>Write the above change to the input file without modifying anything else in the input file.</li> </ol> <p>After running my script, it completely garbled the HTML code in the input file and it cut off the first few characters of each line in the file. This is strange, because I know for sure that $URL_Last only occurs once in each file, so it should only be matched once and replaced once. Is this being caused by a misuse of the seek function?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload