This question already has answers here:
Find and Replace Inside a Text File from a Bash Command
                                
                                    (14个回答)
                                
                        
                                2年前关闭。
            
                    
这是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和filename的行,并删除vmname前双引号后的所有内容
检查“ scsi0:”后该行中的数字,并在下划线后添加/替换该数字,以便P120_vmname_2变为vmname_3


关键是,在vmname之前可以删除任意数量的字符,并且需要修复的行可以位于源文件中的任何位置。

我是否需要将单独的行输出分配给单独的变量,或者仅用一个变量就可以操作它们?

谢谢

最佳答案

您可以将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"

关于arrays - 修复虚拟机和描述 rune 件-重写vmx ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52000922/

10-09 15:16