I have two string variables:
我有两个字符串变量:
@echo off
set string_1=abc def ghj
set string_2=abc_def_ghj
In string_1
I need to replace spaces with %20
, so the result will be:
在string_1中我需要用%20替换空格,结果将是:
abc%20def%20ghj
In string_2
I need to replace _
with spaces, so the result will be:
在string_2中我需要用空格替换_,所以结果将是:
abc def ghj
I need to use batch (.bat) file, what are the options to do this?
我需要使用批处理(.bat)文件,有什么选择呢?
2 个解决方案
#1
You can use string manipulation to replace the characters you want.
您可以使用字符串操作来替换所需的字符。
@echo off
setlocal enabledelayedexpansion
set "string_1=abc def ghj"
set string_2=abc_def_ghj
set new_string_1=!string_1: =%%20!
set new_string_2=%string_2:_= %
echo Old String 1: %string_1%
echo New String 1: %new_string_1%
echo Old String 2: %string_2%
echo New String 2: %new_string_2%
pause
I had to enable delayed expansion in string 1 so that the inner and outer percent signs wouldn't cancel each other out.
我必须在字符串1中启用延迟扩展,以便内部和外部百分号不会相互抵消。
#2
Variable Edit/Replace with minimalized EnableDelayedExpansion scope:
使用最小化的EnableDelayedExpansion范围进行变量编辑/替换:
@ECHO OFF
SETLOCAL enableextensions
set "string_1=1abc def ghj"
SETLOCAL enabledelayedexpansion
set "string_1=!string_1: =%%20!"
ENDLOCAL&set "string_1=%string_1%"
echo %string_1%
set "string_2=2abc_def_ghj"
set "string_2=%string_2:_= %"
echo %string_2%
Note ENDLOCAL&set "string_1=%string_1%"
line (and do not change it).
注意ENDLOCAL并设置“string_1 =%string_1%”行(并且不要更改它)。
Output:
==>30087503.bat
1abc%20def%20ghj
2abc def ghj
#1
You can use string manipulation to replace the characters you want.
您可以使用字符串操作来替换所需的字符。
@echo off
setlocal enabledelayedexpansion
set "string_1=abc def ghj"
set string_2=abc_def_ghj
set new_string_1=!string_1: =%%20!
set new_string_2=%string_2:_= %
echo Old String 1: %string_1%
echo New String 1: %new_string_1%
echo Old String 2: %string_2%
echo New String 2: %new_string_2%
pause
I had to enable delayed expansion in string 1 so that the inner and outer percent signs wouldn't cancel each other out.
我必须在字符串1中启用延迟扩展,以便内部和外部百分号不会相互抵消。
#2
Variable Edit/Replace with minimalized EnableDelayedExpansion scope:
使用最小化的EnableDelayedExpansion范围进行变量编辑/替换:
@ECHO OFF
SETLOCAL enableextensions
set "string_1=1abc def ghj"
SETLOCAL enabledelayedexpansion
set "string_1=!string_1: =%%20!"
ENDLOCAL&set "string_1=%string_1%"
echo %string_1%
set "string_2=2abc_def_ghj"
set "string_2=%string_2:_= %"
echo %string_2%
Note ENDLOCAL&set "string_1=%string_1%"
line (and do not change it).
注意ENDLOCAL并设置“string_1 =%string_1%”行(并且不要更改它)。
Output:
==>30087503.bat
1abc%20def%20ghj
2abc def ghj