使用 PowerShell 脚本编辑 .cfg 文件
Edit .cfg files with PowerShell Script
我有一个看起来像这样的 .cfg 文件
Block 1
attr_1 = 0
attr_2 = "a"
END
Block 2
attr_1 = 0
attr_2 = "b"
END
Block 3
attr_1 = 0
attr_2 = "a"
END
如何使用 powershell 脚本将所有 attr_2 = "a" 的块中的 attr_1 的值更改为 1?
即结果应如下所示:
Block 1
attr_1 = 1 #attr_1 is changed
attr_2 = "a"
END
Block 2
attr_1 = 0
attr_2 = "b"
END
Block 3
attr_1 = 1 #att_1 is changed
attr_2 = "a"
END
我知道对于 XML 文件,powershell 可以更改每个节点的属性,但是如何使用 .cfg 文件完成此操作?我正在使用 Powershell V2.0。感谢您的帮助!
我对 .CFG 文件了解不多,PowerShell 也不了解,但根据您的示例,您可能可以使用正则表达式来完成这项工作。
# Read the file in blocks delimited by lines starting with 'END'
$blocks = Get-Content temp.cfg -Delimiter "`nEND"
# Process those blocks matching a criteria
$blocks = $blocks | ForEach-Object {
if ($_ -match '\battr_2\s*=\s*"a"') {
# replace specified attribute
$_ = $_ -replace '\b(attr_1\s*=)\s*0\b', ' 1'
}
$_
}
# Write the blocks to another file...
$blocks | set-content temp2.cfg -NoNewline
我已经编写了正则表达式,因此它们应该只更改与您的示例非常匹配的部分。
P.S。我还没有仔细检查这是否适用于 PowerShell 2,但我认为是的。此外,根据读取这些文件的内容,您可能需要在 Set-Content 上指定 -Encoding Ascii
(或其他内容)。
我有一个看起来像这样的 .cfg 文件
Block 1
attr_1 = 0
attr_2 = "a"
END
Block 2
attr_1 = 0
attr_2 = "b"
END
Block 3
attr_1 = 0
attr_2 = "a"
END
如何使用 powershell 脚本将所有 attr_2 = "a" 的块中的 attr_1 的值更改为 1?
即结果应如下所示:
Block 1
attr_1 = 1 #attr_1 is changed
attr_2 = "a"
END
Block 2
attr_1 = 0
attr_2 = "b"
END
Block 3
attr_1 = 1 #att_1 is changed
attr_2 = "a"
END
我知道对于 XML 文件,powershell 可以更改每个节点的属性,但是如何使用 .cfg 文件完成此操作?我正在使用 Powershell V2.0。感谢您的帮助!
我对 .CFG 文件了解不多,PowerShell 也不了解,但根据您的示例,您可能可以使用正则表达式来完成这项工作。
# Read the file in blocks delimited by lines starting with 'END'
$blocks = Get-Content temp.cfg -Delimiter "`nEND"
# Process those blocks matching a criteria
$blocks = $blocks | ForEach-Object {
if ($_ -match '\battr_2\s*=\s*"a"') {
# replace specified attribute
$_ = $_ -replace '\b(attr_1\s*=)\s*0\b', ' 1'
}
$_
}
# Write the blocks to another file...
$blocks | set-content temp2.cfg -NoNewline
我已经编写了正则表达式,因此它们应该只更改与您的示例非常匹配的部分。
P.S。我还没有仔细检查这是否适用于 PowerShell 2,但我认为是的。此外,根据读取这些文件的内容,您可能需要在 Set-Content 上指定 -Encoding Ascii
(或其他内容)。