使用 bash shell 脚本挂载映像并编辑配置文件(在文件系统内)
mounting an image and editing a configuring file ( within file system)using bash shell script
我需要挂载一个映像文件(.qcow2 文件)并使用以下内容编辑文件系统中的其中一个文件:
address 192.168.xxx.xxx/24 active
primary-dns xx.x.64.20
dns-domain xxxx.xxtest
static-route xx1.xx.0/18 next-hop xxx.xxx.xxx.x
li-local-save
我编写了以下用于挂载 .qcow2 文件的自动化代码,但不确定是否可以使用 sed 编辑该文件。请帮忙
#!/bin/bash
mkdir mntpt
modprobe nbd max_part=8
qemu-nbd --connect=/dev/nbd0 $PWD/
mount /dev/nbd0p1 mntpt
sed -i "s/^\(address \).*/xxx.xxx.xxx/24 active/g" mntpt/bof.cfg
sed -i "s/^\(primary-dns \).*/x1.64.20/g" mntpt/bof.cfg
sed -i "s/^\(no \).*/li-local-save/g" mntpt/bof.cfg
qemu-nbd --disconnect /dev/nbd0
umount mntpt
写三个单独的 sed 脚本似乎很浪费,而且可能有问题。在 sed 脚本中用换行符或(在某些方言中)分号分隔命令。
此外,如果字符串需要包含斜杠,您需要对字符串中的斜杠进行转义,或者使用不同的分隔符。您可以使用 s:foo:bar:
作为 s/foo/bar/
的同义词(使用任何非字母、非数字字符代替斜杠,真的)。
sed -i 's:^\(address \).*:xxx.xxx.xxx/24 active:
s/^\(primary-dns \).*/x1.64.20/
s/^\(no \).*/li-local-save/' mntpt/bof.cfg
(据我所知,你的 /g
标志是多余的。如果你需要多次替换相同的值 在同一行 ,然后重新添加。)
我需要挂载一个映像文件(.qcow2 文件)并使用以下内容编辑文件系统中的其中一个文件:
address 192.168.xxx.xxx/24 active
primary-dns xx.x.64.20
dns-domain xxxx.xxtest
static-route xx1.xx.0/18 next-hop xxx.xxx.xxx.x
li-local-save
我编写了以下用于挂载 .qcow2 文件的自动化代码,但不确定是否可以使用 sed 编辑该文件。请帮忙
#!/bin/bash
mkdir mntpt
modprobe nbd max_part=8
qemu-nbd --connect=/dev/nbd0 $PWD/
mount /dev/nbd0p1 mntpt
sed -i "s/^\(address \).*/xxx.xxx.xxx/24 active/g" mntpt/bof.cfg
sed -i "s/^\(primary-dns \).*/x1.64.20/g" mntpt/bof.cfg
sed -i "s/^\(no \).*/li-local-save/g" mntpt/bof.cfg
qemu-nbd --disconnect /dev/nbd0
umount mntpt
写三个单独的 sed 脚本似乎很浪费,而且可能有问题。在 sed 脚本中用换行符或(在某些方言中)分号分隔命令。
此外,如果字符串需要包含斜杠,您需要对字符串中的斜杠进行转义,或者使用不同的分隔符。您可以使用 s:foo:bar:
作为 s/foo/bar/
的同义词(使用任何非字母、非数字字符代替斜杠,真的)。
sed -i 's:^\(address \).*:xxx.xxx.xxx/24 active:
s/^\(primary-dns \).*/x1.64.20/
s/^\(no \).*/li-local-save/' mntpt/bof.cfg
(据我所知,你的 /g
标志是多余的。如果你需要多次替换相同的值 在同一行 ,然后重新添加。)