我正在创建一个备份 Web 服务器,但我希望备份服务器只有一个 root 用户。因此,在移动所有数据库后,我需要mysqli_connect(...)
替换db.txt
.
我已经写了:
beg="mysqli_connect("
end=");"
#need to find out the database
db="123"
new="'localhost','root','pass','$db'"
cat db.txt | sed "s/$beg.*$end/$beg$new$end/"
替换所有配置,但我需要找出数据库。我可以通过获取 ' '$end
和前一个 ' '之间的文本来做到这一点,
,但是我将如何使用 sed 来获取它呢?
输入:
潜在文件:
sadnkjnadsjknfaskdjfnlasdnfkdsa
safdjnasdkjjfasndka
asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect("192.168.1.10","dave","password","DavesDB");
sdfnjnweewrewqrfgjdgnf
vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj
mysqli_connect("192.168.1.10" , "tom" , "password" , 'TomsDB'); dsanjasdknfjansd
sakfdnjsadjkfnsa
sknfdsjdnfjsdnnqwerweq
输出:
sadnkjnadsjknfaskdjfnlasdnfkdsa
safdjnasdkjjfasndka
asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect("localhost","root","rootpassword","DavesDB");
sdfnjnweewrewqrfgjdgnf
vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj
mysqli_connect("localhost","root","rootpassword","TomsDB"); dsanjasdknfjansd
sakfdnjsadjkfnsa
sknfdsjdnfjsdnnqwerweq
答案1
您不需要获取数据库名称,用它本身替换某些内容是没有意义的。保持不变即可:
beg="mysqli_connect("
new="'localhost','root','pass',"
sed "s/$beg\([^,]\+,\)\{3\}/$beg$new/" file
如果我将您给出的示例保存为file
,则会返回:
$ sed "s/$beg\([^,]\+,\)\{3\}/$beg$new/" file
sadnkjnadsjknfaskdjfnlasdnfkdsa
safdjnasdkjjfasndka
asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect('localhost','root','pass',"DavesDB");
sdfnjnweewrewqrfgjdgnf
vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj
mysqli_connect('localhost','root','pass', 'TomsDB'); dsanjasdknfjansd
sakfdnjsadjkfnsa
sknfdsjdnfjsdnnqwerweq
正sed
则表达式查找$beg
,然后查找三个 non- 实例,,
后跟一个逗号 ( \([^,]\+,\)\{3\}
),并将它们替换为$beg$new
。数据库名称保持原样,因为没有理由更改它。
(
您还可以通过删除来稍微简化语法,$beg
从中可以使用 sed 的扩展正则表达式语法:
$ sed -E "s/$beg\(([^,]+,){3}/$beg($new/" file
sadnkjnadsjknfaskdjfnlasdnfkdsa
safdjnasdkjjfasndka
asfdknjdsakjfnasjdnkfsadnjkads mysqli_connect('localhost','root','pass',"DavesDB");
sdfnjnweewrewqrfgjdgnf
vncnccnvxjncvjn4wrwerewrewerwjvcnxjnvcj
mysqli_connect('localhost','root','pass', 'TomsDB'); dsanjasdknfjansd
sakfdnjsadjkfnsa
sknfdsjdnfjsdnnqwerweq