CMD正则表达式

时间:2012-11-29 07:22:39

标签: windows command-line

我正在尝试创建一个带有正则表达式的命令行(或.bat文件),该表达式必须用(单个空格字符)替换*(多个空格字符)。仅使用单个空格字符替换多个空格字符。在Unix中我们可以使用sed。但是在我们的情况下,这是不可能的,并且安装sed不是一种选择。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

@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% 

这应该适用于大多数情况。如果你的文件有很多空格,你需要用?添加更多的表达式(也可以插入for循环但这更容易: - ))。