How to trim leading and trailing white-spaces by a single command?
假设您在变量
例如,字符串是(这里的
1 | " two spaces, trimmed text string, space-tab-space _" |
预期的输出是(双引号又不是字符串的一部分):
1 | "two spaces, trimmed text string, space-tab-space" |
如何做到这一点?
在这种情况下,当我说"空格"时,我指的是空格和(水平)制表符。
不可能在一行中同时修剪空格和制表符,但对于空格,您可以使用此技巧:
1 2 3 4 5 6 7 8 9 10 | @echo off setlocal EnableDelayedExpansion set"x= two spaces, trimmed text string, space-space-space " echo"%x%" rem The single line: set"word=%x: =" & (if"!word!" neq"" set"x2=!x2! !word!") & set"word=%" & set"x2=!x2:~1!" echo"%x2%" |
仅针对前导空格,以下代码有效(_ 表示 TAB):
1 2 3 4 5 6 | set"STRING= two spaces, trimmed text string, space-tab-space _" rem no"delims=" option given, so defaulting to spaces and tabs: for /F"tokens=* eol=" %%S in ("%STRING%") do set"LEFTTRIMMED=%%S" echo"%LEFTTRIMMED%" |
然而,尾随的空格仍然存在;但它们可以通过此线程中显示的方法删除。