2

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

set /p用来获取变量。

如果用户输入:

------what-----is---------my--------ip---------                        

...------空格在哪里,我想得到以下结果:

what is my ip

(单词之间只有一个空格)

4

4 回答 4

4

你可以这样做:

@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
于 2013-02-27T14:27:27.547 回答
3

没有简单的本机批处理命令可以完全满足您的要求。Batch 在文本操作方面相当薄弱。但它可以用一小块本机批处理代码来完成。

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

@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!'

您可以下载各种实用程序以使工作更轻松。例如,免费的 Windows 版 Gnu sed可以解决这个问题。

一些办公室不允许使用下载的可执行文件。我编写了一个名为 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));
    }
  }
}
于 2013-02-28T01:35:10.917 回答
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
于 2014-04-21T22:23:22.147 回答
0

我不是专家,但这是我喜欢这样做的方式:

@ECHO OFF
:retry
ECHO.

SET str=
SET /P str=Type text here: 
IF NOT DEFINED str GOTO retry

:: remove double spaces
:remove_double_spaces
IF NOT "%str%" == "%str:  =%" SET str=%str:  = %&& GOTO remove_double_spaces

:: retry if nothing but spaces
IF "%str%" == " " GOTO retry

:: remove leading space
IF "%str:~0,1%" == " " SET str=%str:~1%

:: remove trailing space
IF "%str:~-1%" == " " SET str=%str:~0,-1%

ECHO "%str%"
GOTO retry
于 2021-10-29T00:56:55.540 回答