修复虚拟机和描述符文件-重写vmx

时间:2018-08-24 09:00:29

标签: arrays linux bash shell

这是grep -E“ scsi0:” * .vmx的输出。我的目录之一中的grep -E“ fileName”命令:

scsi0:0.fileName = "vmname.vmdk"
scsi0:1.fileName = "vmname_1.vmdk"
scsi0:2.fileName = "vmname_2.vmdk"
scsi0:3.fileName = "P120_vmname_2.vmdk"
scsi0:4.fileName = "P120_vmname_3.vmdk"

我需要在该vmx文件中重写以上输出,以便使其看起来像下面的

scsi0:0.fileName = "vmname.vmdk"
scsi0:1.fileName = "vmname_1.vmdk"
scsi0:2.fileName = "vmname_2.vmdk"
scsi0:3.fileName = "vmname_3.vmdk"
scsi0:4.fileName = "vmname_4.vmdk"

因此,实质上,脚本需要满足以下条件:

  • 查找包含 scsi0 文件名的行,并删除在 vmname
  • 前双引号后的所有内容
  • 检查“ scsi0:”后该行中的数字是多少,并在下划线后添加/替换该数字,以便P120_vmname_2成为vmname_3

问题在于, vmname 之前可以有任意数量的字符需要删除,而需要修复的行可以位于源文件中的任何位置。

我需要将单独的行输出分配给单独的变量,还是可以只用一个变量来操纵它们?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以将grep的输出通过管道传输到sed吗?

如果是这样,则可以这样替换:

sed -r 's/^(.*:)([[:digit:]]+)(.*) = \".*vmname_[[:digit:]]+/\1\2\3 = \"vmname_\2/'
#           ^        ^         ^       ^             ^          ^              ^
#           |        |         |       |             |          |              Replace number.
#           |        |         |       |             |          Re-create line start
#           |        |         |       |             Match incorrect number                        
#           |        |         |       Match garbage before "vmname"
#           |        |         Match Filename
#           |        Correct number
#           Line start

因此您的实际命令将如下所示:

grep -E "scsi0:" *.vmx | grep -E "fileName" | \
sed -r 's/^(.*:)([[:digit:]]+)(.*) = \".*vmname_[[:digit:]]+/\1\2\3 = \"vmname_\2/'

将其转换为

scsi0:0.fileName = "vmname.vmdk"
scsi0:1.fileName = "vmname_1.vmdk"
scsi0:2.fileName = "vmname_2.vmdk"
scsi0:3.fileName = "P120_vmname_2.vmdk"
scsi0:4.fileName = "P120_vmname_3.vmdk"
scsi0:5.fileName = "P12asdasdsada_asdasd_sdsad0_vmname_3.vmdk"
scsi0:6.fileName = "vmname_3.vmdk"

对此:

scsi0:0.fileName = "vmname.vmdk"
scsi0:1.fileName = "vmname_1.vmdk"
scsi0:2.fileName = "vmname_2.vmdk"
scsi0:3.fileName = "vmname_3.vmdk"
scsi0:4.fileName = "vmname_4.vmdk"
scsi0:5.fileName = "vmname_5.vmdk"
scsi0:6.fileName = "vmname_6.vmdk"