Removing double quotes from variables in batch file creates problems with CMD environment

前端 未结 11 574
春和景丽
春和景丽 2020-12-04 11:25

Can anybody help with effective and safe way of removing quotes from batch variables?

I have written a batch file which successfully imports a list of parameters %1,

11条回答
  •  春和景丽
    2020-12-04 11:38

    The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

    SET xyz=%~1
    

    Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

    But, This simple tilde syntax will not work for other variables that were not passed in as parameters

    For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

    @SET SomeFileName="Some Quoted file name"
    @echo %SomeFileName% %SomeFileName:~1,-1%
    

    If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

    @SET VAR="Some Very Long Quoted String"
    If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
    

提交回复
热议问题