批处理文件替换用户输入的字符串变量

时间:2015-02-26 17:16:25

标签: batch-file

我正在尝试使用批处理脚本来允许用户输入的数据替换.js文件中的变量。

我在完成脚本删除文件中的所有数据时遇到问题。

我正在寻找一种快速简便的方法,可以根据用户输入的值重复查找和替换.js文件中的字符串。


以下是我尝试的脚本:

@echo off > header.js
setLocal DisableDelayedExpansion

::Declare variables and user entry
::if exist header.js ren header.js
set /p FolderLinkName= Folder Link Name? 
set /p PropertyName= Property Name? 
set /p PropertyAddress1= Property Address 1? 
set /p PropertyAddress2= Property Address 2? 
set /p PropertyCity= Property City? 
set /p PropertyState= Property State? 
set /p PropertyZip= Property Zip? 
set /p PropertyContactName = Property Contact Name? 
set /p PropertyPhone = Property Phone? 
set /p PropertyPhoneExt = Property Phone Ext? 
set /p PropertyEmail = Property Email? 

::String Replacements

for /f "tokens=* delims= " %%G in (header.js) do (
    set str=%%G
    setLocal EnableDelayedExpansion
    set str=!str:[var propertyFolderLink = "propertycopy";]=[var propertyFolderLink = "[%FolderLinkName%]";]!
    set str=!str:[var propertyName = "PROPERTY COPY";]=[var propertyName = "[%PropertyName%]";]!
    set str=!str:[var propertyAddress1 = "3050 Biscayne Blvd";]=[var propertyAddress1 = "[%PropertyAddress1%]";]!
    set str=!str:[var propertyAddress2 = "Suite 602";]=[var propertyAddress2 = "[%PropertyAddress2%]";]!
    set str=!str:[var propertyCity = "Miami";]=[var propertyCity = "[%PropertyCity%]";]!
    set str=!str:[var propertyState = "FL";]=[var propertyState = "[%PropertyState%]";]!
    set str=!str:[var propertyZip = "33137";]=[var propertyZip = "[%PropertyZip%]";]!
    set str=!str:[var propertyContact = "Property Manager";]=[var propertyContact = "[%PropertyContactName%]";]!
    set str=!str:[var propertyPhone = "(555) 555-55555";]=[var propertyPhone = "[%PropertyPhone%]";]!
    set str=!str:[var propertyPhoneExt = "";]=[var propertyPhoneExt = "[%PropertyPhoneExt%]";]!
    set str=!str:[var propertyEmail = "email@email.com";]=[var propertyEmail = "[%PropertyEmail%]";]!
    >> header.js echo(!str!
    endlocal
)

1 个答案:

答案 0 :(得分:0)

清除文件的原因是此行。

  

@echo off> header.js

@echo off(空字符串)的输出正在替换header.js中的所有文本。然后,当您尝试使用for语句从文件中读取行时,无法读取任何内容。删除此行的> header.js部分。

相反,将所有输出写入新文件header.js.output,然后在脚本的最末端将其复制到原始文件上。

其次,SET命令几乎不像你在这里尝试那样聪明。它只是在第一个等号之后对所有内容进行精确的字符串匹配,并且(例如)将用[var propertyFolderLink

替换文本"propertycopy";]=[var propertyFolderLink = "[%FolderLinkName%]";]

要使用更复杂的表达式替换文本,您需要使用基于正则表达式的应用程序(如sedjrepl)进行替换。

或者,可以在PowerShell中重写整个脚本以使其更简单,更强大。如果你想尝试,那么How can I replace every occurrence of a String in a file with PowerShell?应该可以帮助你开始。