如何仅批量替换一个字符串实例

时间:2018-12-21 21:21:13

标签: batch-file

我已经在整个互联网上进行了搜索,但无济于事。您如何只批量替换一个发现的字符串?假设我有以下代码:

SET string=chair chair book

有没有办法只替换一次“椅子”一词?要这样吗?

chair book

我这样做时使用了编辑替换功能

SET furniture=%string:chair=%

但是,这使得椅子的所有实例都消失了

book

你们有没有解决的办法?

编辑:很抱歉,我的意思是替换了字符串的 first 实例。例如,给定

chair chair chair book

然后显示“椅子”一词

chair chair book

对于第二个想法,我想我当时只希望替换一个单词。所以给定“椅子”

table desk chair chair book chair candle lamp lamp desk

应该是

table desk chair book chair candle lamp lamp desk

对于这种混乱,我真的感到很抱歉,希望这可以解决!

谢谢, 猪油菌

1 个答案:

答案 0 :(得分:0)

这可以通过简单的for循环来完成。直接从this postStephan的示例中获取我提供的代码-我们从您的String中提取每个单词,然后简单地检查单词池中是否已经使用了它。

RemoveAllDuplicateWords.bat

@ECHO OFF
@setlocal EnableDelayedExpansion

Set "String=table desk chair chair book chair candle lamp lamp desk"
set "newstring="

for %%i in (%string%) do (
  echo !newstring!|findstr /i "\<%%i\>" >nul || set "newstring=!newstring! %%i"
)
Set "furniture=%newstring:~1%"

Echo %furniture%

如斯蒂芬所说,如果您希望过滤器区分大小写,请删除/i


编辑:

因此,由于对线程请求的误解,我带来了一个EDIT,它将解决用户的帖子(希望如此)。从他的澄清中,他/她希望不从字符串中删除重复的单词,而是在彼此之间删除重复的单词。

之前table desk chair chair book chair candle lamp lamp desk

之后: table desk chair book chair candle lamp lamp desk

此过程很简单,但可能会变得复杂。我这样做的过程是简单地比较字符串中出现的每个单词。这将需要Table Chair Chair DeskTable Chair Chair Chair DeskTable Chair Chair Chair Chair Desk(您明白了)并将其更改为Table Chair Desk

因为此脚本很长,所以您不想为每个字符串粘贴此脚本。一个很棒的解决方案是call。当我把它变成一个函数。在下面,我将解释如何使用它。

命令: Call :RemoveMultipleWords [String You Want Edited] [New String]

示例: Call :RemoveMultipleWords String Furniture

请记住,您也可以自己编辑原始字符串。这意味着您可以放String Furniture而不是String String

RemoveOnlyDouble + Instances.bat:

@ECHO OFF
@setlocal EnableDelayedExpansion

Rem | Original String's
Set "Furniture=table desk chair chair book chair candle lamp lamp desk"
Set "Food=Lasagne Fettuccine_Alfredo Carbonara Carbonara Culatello Breadsticks Tortano Tortano"

Rem | Call To Fix Function
Call :RemoveMultipleWords Furniture Furniture
Echo !Furniture!

Call :RemoveMultipleWords Food IntlianFoods
Echo !IntlianFoods!

Rem | Exit BATCH
Pause
Exit /b

:RemoveMultipleWords
Rem | Reset LoopCount
Set "LoopCount=0"

Rem | Process Each Item
for %%A in (!%1!) do (

    Rem | Get Current Word
    Set "CurrentWord=%%A"

    Rem | Set First Word
    If "!LoopCount!"=="0" (

        Rem | Set LoopCount
        Set "LoopCount=1"

        Rem | First Run
        Set "%2=%%A"

    ) ELSE (

        Rem | Upcoming Runs
        If "!LoopCount!"=="1" (

            Rem | First Word
            Set "LastWord1=%%A"

            Rem | Add LoopCount
            Set "LoopCount=2"

            Rem | Echo Results
            If not "!LastWord2!"=="%%A" (Set "%2=!%2! !CurrentWord!")

        ) ELSE (

            Rem | Next Word
            Set "LastWord2=%%A"

            Rem | Subtract LoopCount
            Set "LoopCount=1"

            Rem | Echo Results
            If not "!LastWord1!"=="%%A" (Set "%2=!%2! !CurrentWord!")

        )
    )
)
Goto :EOF