How can I replace a single line several times with several different values ​​in Perl?

I use this one-line Perl (in bash) to successfully replace a string with a random one in a given file:

perl -pi -e "s/replace\ this/`</dev/urandom tr -dc A-Za-z0-9 | head -c64`/g" example.php

However, I do not know how to replace several “replace this” with different random strings.

+3
source share
2 answers
perl -pi -e 's/replace this/join "", map { ("a" .. "z", "A" .. "Z", 0 .. 9)[rand(62)] } 1 .. 64/eg' example.php

Let me break it into pieces.

("a" .. "z", "A" .. "Z", 0 .. 9)

is a list containing the characters you want to use in a random string.

[rand(62)]

( rand). 62 . rand , . , Perl 5, . , , , .

map . . 1 .. 64, . , , map .

join , (, join ",", "a", "b", "c" "a,b,c"). , , (.. ).

. (- /g) "replace this" (- /e) "replace this" , ( join).

+10

script

#!/bin/bash
for replace in "replace this" "replace that"
do
   rand=$(generate random here  using /dev/urandom )
   sed -i "s/$replace/$rand/" file
done
0

Source: https://habr.com/ru/post/1768232/


All Articles