删除双空格并用一个替换它们

时间:2013-02-27 11:38:56

标签: batch-file

我需要从执行的命令中删除空格

我使用集/p来获取变量

如果用户输入:

------What-----is---------my--------ip---------                        

其中------是空格,我想执行像这样的命令

what is my ip

(它们之间只有一个空格)

4 个答案:

答案 0 :(得分:3)

你可以这样做:

@ECHO OFF
SET /P x=
FOR /F "tokens=*" %%i IN ('ECHO %x%') DO SET y=%%i
ECHO original input  : %x%
ECHO spaces condensed: %y%

输入字符串

      What     is         my        ip

返回

original input  :       What     is         my        ip
spaces condensed: What is my ip

答案 1 :(得分:3)

没有简单的本机批处理命令可以完全按照您的意愿执行。在文本操作方面,批处理相当薄弱。但是可以使用一小块本机批处理代码完成。

这是一个纯批量解决方案。代码用循环中的单个空格替换双空格,直到不再存在双空格。然后它删除任何前导和尾随空格。我选择使用延迟扩展,因为这可以消除& < >等特殊字符的问题。

@echo off
setlocal enableDelayedExpansion
set "str="
set /p "str=Enter a string: "
echo before: '!str!'

:: **** Begin space compression code ****
:loop
if defined str (
  set "new=!str:  = !"
  if "!new!" neq "!str!" (
    set "str=!new!"
    goto :loop
  )
)
if defined str if "!str:~0,1!" equ " " set "str=!str:~1!"
if defined str if "!str:~-1!" equ " " set "str=!str:~0,-1!"
:: **** End space compression code ****

echo after:  '!str!'

您可以下载各种实用程序,以简化工作。例如,免费Gnu sed for Windows可以解决问题。

某些办事处不允许使用下载的可执行文件。我编写了一个名为REPL.BAT的混合JScript /批处理脚本,它对文本操作非常有用。它提供了方便的正则表达式搜索和替换功能,它只使用本机Windows命令,不需要任何安装。所以在任何地方都可以使用它。

这是一个使用REPL.BAT实用程序的解决方案。它比上面的纯批次解决方案短得多,并且不需要延迟扩展。 (我会暂时启用延迟扩展,以便可靠地回显该值)

@echo off
setlocal disableDelayedExpansion
set "str="
set /p "str=Enter a string: "

call :displayValue "before:" str

:: **** Begin space compression code ****
for /f "eol= tokens=* delims= " %%A in (
  'repl "  *" " " s str ^| repl " $" ""'
) do set "str=%%A"
:: **** End space compression code ****

call :displayValue "after: " str
exit /b


:displayValue
setlocal enableDelayedExpansion
echo %~1 '!%~2!'
exit /b

第一个REPL命令读取环境变量并将连续的空格转换为单个空格。该结果通过管道输入第二个REPL命令,删除任何尾随空格。最后,它的输出由FOR / F命令处理,该命令删除前导空格。

这是上面代码所依赖的REPL.BAT实用程序。完整的文档嵌入在脚本中。

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?
:::
:::  Performs a global search and replace operation on each line of input from
:::  stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /? then prints help documentation
:::  to stdout.
:::
:::  Search  - By default this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::            A $ literal can be escaped as $$. An empty replacement string
:::            must be represented as "".
:::
:::            Replace substitution pattern syntax is documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            I - Makes the search case-insensitive.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in Replace are
:::                treated as $ literals.
:::
:::            E - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line. ^ anchors
:::                the beginning of a line and $ anchors the end of a line.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences:
:::
:::                \\     -  Backslash
:::                \b     -  Backspace
:::                \f     -  Formfeed
:::                \n     -  Newline
:::                \r     -  Carriage Return
:::                \t     -  Horizontal Tab
:::                \v     -  Vertical Tab
:::                \xnn   -  Ascii (Latin 1) character expressed as 2 hex digits
:::                \unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Escape sequences are supported even when the L option is used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string.
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    findstr "^:::" "%~f0" | cscript //E:JScript //nologo "%~f0" "^:::" ""
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 1
  )
)
echo(%~3|findstr /i "[^SMILEX]" >nul && (
  call :err "Invalid option(s)"
  exit /b 1
)
cscript //E:JScript //nologo "%~f0" %*
exit /b 0

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var env=WScript.CreateObject("WScript.Shell").Environment("Process");
var args=WScript.Arguments;
var search=args.Item(0);
var replace=args.Item(1);
var options="g";
if (args.length>2) {
  options+=args.Item(2).toLowerCase();
}
var multi=(options.indexOf("m")>=0);
var srcVar=(options.indexOf("s")>=0);
if (srcVar) {
  options=options.replace(/s/g,"");
}
if (options.indexOf("e")>=0) {
  options=options.replace(/e/g,"");
  search=env(search);
  replace=env(replace);
}
if (options.indexOf("l")>=0) {
  options=options.replace(/l/g,"");
  search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
  replace=replace.replace(/\$/g,"$$$$");
}
if (options.indexOf("x")>=0) {
  options=options.replace(/x/g,"");
  replace=replace.replace(/\\\\/g,"\\B");
  replace=replace.replace(/\\b/g,"\b");
  replace=replace.replace(/\\f/g,"\f");
  replace=replace.replace(/\\n/g,"\n");
  replace=replace.replace(/\\r/g,"\r");
  replace=replace.replace(/\\t/g,"\t");
  replace=replace.replace(/\\v/g,"\v");
  replace=replace.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
    function($0,$1,$2){
      return String.fromCharCode(parseInt("0x"+$0.substring(2)));
    }
  );
  replace=replace.replace(/\\B/g,"\\");
}
var search=new RegExp(search,options);

if (srcVar) {
  WScript.Stdout.Write(env(args.Item(3)).replace(search,replace));
} else {
  while (!WScript.StdIn.AtEndOfStream) {
    if (multi) {
      WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(search,replace));
    } else {
      WScript.Stdout.WriteLine(WScript.StdIn.ReadLine().replace(search,replace));
    }
  }
}

答案 2 :(得分:0)

这就是我如何证明它(使用延迟扩展):

@ECHO OFF
setlocal enableextensions enabledelayedexpansion
SET /P str=
for /l %%i in (1,1,31) do set str=!str:  = !
ECHO spaces condensed: !str!

我用循环中的一个替换两个连续的空格 - 假设你有8个空格的字符串。然后它变成:

1        1
1    1
1  1
1 1

我知道它不是通用的,但效果很好(最多2 ^ 31个空格)。要处理领先的空间,你可以使用这个技巧(见www.dostips.com):

for /f "tokens=* delims= " %%a in ("!str!") do set str=%%a

答案 3 :(得分:0)

尝试50次(应该足够,如果不增加50次)

for %%n in (1,1,50) do set str=!str:  = !"