简体   繁体   中英

CMD Regular expression

I am trying to create a command line (or .bat file) with a regular expression which has to replace * (multiple space characters) with (single space character). Replace multiple space characters with only a single space character. In Unix we can use sed. However in our case this is not possible and installing sed is not an option. Any ideas?

@echo off
set file_name_with_spaces="_ file    name   _.txt"

rem --- '?' is forbidden in file names ---
set file_name_with_no_spaces=%file_name_with_spaces: =?%
echo %file_name_with_no_spaces%

rem --- we need to to replace the quewstion marks that have primer numbers count and their modulus --
set file_name_with_no_spaces=%file_name_with_no_spaces:??=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:???=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:?????=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:???????=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:????????????=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:???????=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:???????=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:???=?%
set file_name_with_no_spaces=%file_name_with_no_spaces:??=?%

set file_name_with_single_spaces=%file_name_with_no_spaces:?= %
rem ---  ---

echo %file_name_with_single_spaces%
ren %file_name_with_spaces% %file_name_with_single_spaces% 

this should work in the most cases.If you have files with reeeeeeally a lot of spaces you'll need to add more expressions with ? (the also could be inserted in for loop but this was easier :-) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM