<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'hostname',
'login' => 'username',
'password' => 'password',
'database' => 'database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'hostname',
'login' => 'username',
'password' => 'password',
'database' => 'database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
}
登录,密码和数据库中有一些默认值。如何编写脚本来编辑登录名,密码和数据库?
答案 0 :(得分:2)
php文件包含您的示例文本:
kent$ awk '/login/{l++;if(l>1)gsub(/root/,"newLogin");}
/password/{p++;if(p>1)gsub(/xxx/,"newPwd");}
/database/{d++;if(d>1)gsub(/xxx/,"newDB");} 1' php
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'xxx',
'database' => 'xxx',
'prefix' => '',
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'newLogin',
'password' => 'newPwd',
'database' => 'cake_test_db',
'prefix' => '',
//'encoding' => 'utf8',
);
}
这只会在$ default块之后更改块。并且,仅默认值将被更改。例如在$ test中,'database' => 'cake_test_db'
该值不是默认的'xxx',因此不会更改。
如果你愿意,你可以在变量中加入新值,并使用-v。
传递给awk修改强>
如果你想改变所有的值,(包括$ default block),它会更容易,检查下面的行:(与上面相同,只会改变defalut值(root,xxx,xxx)。
kent$ awk '/login/{gsub(/root/,"newLogin");}
/password/{gsub(/xxx/,"newPwd");}
/database/{gsub(/xxx/,"newDB");} 1' php
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'newLogin',
'password' => 'newPwd',
'database' => 'newDB',
'prefix' => '',
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'newLogin',
'password' => 'newPwd',
'database' => 'cake_test_db',
'prefix' => '',
//'encoding' => 'utf8',
);
}
<强> EDIT2 强>
这适用于您的新示例。
sed '/login/{s/username/newLOGIN/}; /password/{s/password/newPWD/2}; /database/{s/database_name/newDB/}' php
<?php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'hostname',
'login' => 'newLOGIN',
'password' => 'newPWD',
'database' => 'newDB',
'prefix' => '',
//'encoding' => 'utf8',
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'hostname',
'login' => 'newLOGIN',
'password' => 'newPWD',
'database' => 'newDB',
'prefix' => '',
//'encoding' => 'utf8',
);
}
答案 1 :(得分:1)
#!/usr/bin/awk -f
BEGIN { FS="'"
usr[0] ="usr1" ; usr[1] = "user2"
pass[0] ="pass1" ; pass[1] = "pass2"
db[0] ="db1" ; db[1] = "db2"
}
{
if ($2 == "login") {
$0="\t'login' => '" usr[u] "',"
u++
}
if ($2 == "password") {
$0="\t'password' => '" pass[p] "',"
p++
}
if ($2 == "database") {
$0="\t'database' => '" db[d] "',"
d++
}
print
}