Windows批处理文件中变量的大写第一个字符

时间:2019-07-04 06:42:28

标签: batch-file

我想使用Windows批处理文件将字符串中的第一个字符大写。

set foo="bar"

//uppercase first character

echo %foo%;

预期输出:Bar

2 个答案:

答案 0 :(得分:2)

@ECHO OFF
SETLOCAL
SET "foo=bar"
SET foo
:: get first character
SET "c1=%foo:~0,1%"
:: make it uppercase. Note that the string-substitution is case-insensitive on the 
:: "from" string, but replaces literally.
:: Obviously, A B C should be the full alphabet, which I assign as a user-defined environment string
:: bizarrely called "alphabet"
FOR %%s IN (A B C) DO CALL SET "c1=%%c1:%%s=%%s%%"
SET "foo=%c1%%foo:~1%"
SET foo
GOTO :EOF

将带引号的字符串分配给变量使变量难以逻辑组合。根据需要插入引号要简单得多。

使用语法SET "var=value"(值可能为空)来确保分配的值中不包括任何杂散的尾随空格。

魔术在行中

FOR %%s IN (A B C) DO CALL SET "c1=%%c1:%%s=%%s%%"

它将尝试为字符串%%s中发现的每个%%s(不区分大小写)执行“替换文字c1。在这种情况下,我选择调用{{1 call中的}}子级,以避免set传奇的复杂性。

答案 1 :(得分:0)

借助@Magoo答案,我编写了一个简单的逻辑脚本来实现相同的目的。

 @echo off & SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
    SET STR=bar
:: Taking the rest of the string as it is as we don't need to change that.
    set "restStr=%STR:~1,20%"
:: Taking the first character of the string and doing it to upper case.
    set upper=
    set "str=%STR:~0,1%"
    for /f "skip=2 delims=" %%I in ('tree "\%str%"') do if not defined upper set "upper=%%~I"
    set "upper=%upper:~3%"
:: Printing the result by concating both of them.
    echo %upper%%restStr%
    pause

输出为:酒吧