如何通过单个命令修剪前导和尾随空格? [英] How to trim leading and trailing white-spaces by a single command?

查看:71
本文介绍了如何通过单个命令修剪前导和尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在变量STRING中有一个字符串值,如何使用单个命令(行)删除开头和结尾的空格?

Supposing you have a string value in a variable STRING, how can you remove leading and trailing whitespaces with a single command (line)?

例如,字符串为(_代表制表符;双引号仅用于说明,而不是字符串值的一部分):

For instance, the string is (the _ stands for tab here; double-quotes just for illustration, not part of string value):

"  two spaces, trimmed text string, space-tab-space _ "

期望的输出是(再次双引号不是字符串的一部分):

The expected output is (double-quotes again not part of string):

"two spaces, trimmed text string, space-tab-space"

如何做到这一点?

在这种情况下,我说的空白"是指空格和(水平)制表符.

In this context, I'm talking about spaces and (horizontal) tabulators when I say "whitespaces".

推荐答案

不可能在一行中同时修剪选项卡,但是仅对于空格,您可以使用此技巧:

It is not possible to trim both spaces and tabs in a single line, but just for spaces you may use this trick:

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

这篇关于如何通过单个命令修剪前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆