如何从名单列表中创建多个txt / php文件?

时间:2016-03-12 00:18:04

标签: php wordpress shell batch-file scripting

我有一个文本文件调用newsites.txt里面有一堆名字,我想用来创建一个新的wp-config.php文件(wordpress文件)。

newsites.txt的内容

var routes = {
               '/home': function() { launchModule("Home") },
               '/confirmation': function() { launchModule("Confirmation") }
             };

wp-config.php的内容

    UserName:DatabaseName:DatabasePassword
    UserName2:DatabaseName2:DatabasePassword2

我只需要替换wp-config.php中的这3个字段并将其保存为 UserName -wp-config.php并循环遍历列表的其余部分。

任何想法我可以使用什么来自动化这个?我试着寻找批处理脚本,但不知道如何找到并替换' php文件中的代码。谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用简单的PHP脚本执行此操作:

<?
$template = file_get_contents("wp-config.php");
$arrSearch = [ "database_name_here", "username_here", "password_here" ];
$content = file_get_contents("newsites.txt");
$arrLines = explode("\n", str_replace("\r\n", "\n", $content));

foreach ($arrLines as $line) {
    $arrLine = explode(":", $line);
    $userName = $arrLine[0];
    $dbName = $arrLine[1];
    $password = $arrLine[2];

    $arrReplace = [ $dbName, $userName, $password ];
    $new = str_replace($arrSearch, $arrReplace, $template);
    $filename = "{$userName}-wp-config.php";
    file_put_contents($filename, $new);
}

答案 1 :(得分:0)

你能修改wp-config.php文件吗?如果是这样,那么你可以使用一个有趣的技巧,以一种非常简单的方式解决这个问题。在这个问题中,您使用wp-config.php作为模板,并且您希望替换某些给定位置的文本。诀窍在于将那些地方的名称批处理变量放在感叹号中,并启用延迟扩展;例如:

/** The name of the database for WordPress */
define('DB_NAME', '!database_name_here!');
/** MySQL database username */
define('DB_USER', '!username_here!');
/** MySQL database password */
define('DB_PASSWORD', '!password_here!');

这样,当显示文件的行时,每个!variable_name!将被自动替换变量的值!此方法避免显式查找每个字符串并按每个替换值更改它。

@echo off
setlocal EnableDelayedExpansion

rem Process all lines in newsites.txt
for /F "tokens=1-3 delims=:" %%a in (newsites.txt) do (

   rem Assign values for the corresponding variables
   set "username_here=%%a"
   set "database_name_here=%%b"
   set "password_here=%%c"

   rem Using the values of previous variables
   rem just read and write the lines in wp-config.php;
   rem the variables will be replaced by their values because Delayed Expansion
   (for /F "delims=" %%d in (wp-config.php) do (
      echo %%d
   )) > "!username_here!-wp-config.php"
   echo "!username_here!-wp-config.php" file created

)

输出示例:

C:\> test.bat
"UserName-wp-config.php" file created
"UserName2-wp-config.php" file created

C:\> type UserName-wp-config.php
/** The name of the database for WordPress */
define('DB_NAME', 'DatabaseName');
/** MySQL database username */
define('DB_USER', 'UserName');
/** MySQL database password */
define('DB_PASSWORD', 'DatabasePassword');

C:\> type UserName2-wp-config.php
/** The name of the database for WordPress */
define('DB_NAME', 'DatabaseName2');
/** MySQL database username */
define('DB_USER', 'UserName2');
/** MySQL database password */
define('DB_PASSWORD', 'DatabasePassword2');