我有两个档案 的properties.txt
key1=value1
key2=value2
和使用此文件的template.txt
$key1 xcvsdf sfd $key1 sdf
$key2 lorem $key2 ipsum
我想用properties.txt替换properties.txt中的所有属性并将其写入文件。 我不希望它在python \ java运行时运行,因为它应该在没有先决条件的任何机器上运行
如何使用PowerShell做到这一点?批处理文件?
答案 0 :(得分:3)
假设这需要能够在PowerShell 2.0上运行,这就是我要做的:
# Read template from file
$template = Get-Content .\template.txt
# Copy template to result variable
$result = $template
# Loop through list of properties
Get-Content C:\dev\properties.txt |ForEach-Object{
# Split each line into key-value pairs
$key,$value = $_ -split '=',2
# Replace the placeholder with the appropriate value
$result = $result -replace ('\${0}' -f $key),$value
}
# Output final result
$result |Out-File .\result.txt
答案 1 :(得分:2)
@echo off
setlocal EnableDelayedExpansion
rem Load the set of replacement values from properties.txt
set "n=0"
for /F "tokens=1,2 delims==" %%a in (properties.txt) do (
set /A n+=1
set "key[!n!]=%%a"
set "value[!n!]=%%b"
)
rem Process template.txt file
(for /F "delims=" %%a in (template.txt) do (
set "line=%%a"
rem Process each replacement value
for /L %%i in (1,1,%n%) do (
for /F "tokens=1,2" %%x in ("!key[%%i]! !value[%%i]!") do (
set "line=!line:$%%x=%%y!"
)
)
echo !line!
)) > output.txt
output.txt的:
value1 xcvsdf sfd value1 sdf
value2 lorem value2 ipsum
此代码删除template.txt文件中可能出现的感叹号。如果需要,这一点可以修复。