如何在Windows批处理脚本中将%USERNAME%的值转换为小写?

29

我正在使用一个批处理脚本来自动化一些源代码控制软件功能,但由于我们的svn repos托管在*NIX盒子中,我面临着这两个世界之间永恒的大小写问题。

是否有任何cmd.exe函数可以将Windows系统变量%USERNAME%的值转换为小写?

非常感谢您提前的帮助!


请参见http://www.robvanderwoude.com/battech_convertcase.php。 - Vadzim
9个回答

18

我在查找一些语法时偶然发现了这个页面。我知道它已经过时了,但我想休息一下,给大脑一个小刺激。

这里有一个更短、更易管理的方法。这只是将所有大写字母强制转换为小写字母,而不考虑实际字母是否存在于字符串中。因此,无论字符串的长度如何,函数循环都会精确地运行 26 次。

希望这对某人有所帮助。

@echo off
cls
setlocal enabledelayedexpansion

REM ***** Modify as necessary for the string source. *****
set "_STRING=%*"
if not defined _STRING set "_STRING=%USERNAME%"
set _STRING
REM ***** Modify as necessary for the string source. *****

set "_UCASE=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "_LCASE=abcdefghijklmnopqrstuvwxyz"

for /l %%a in (0,1,25) do (
   call set "_FROM=%%_UCASE:~%%a,1%%
   call set "_TO=%%_LCASE:~%%a,1%%
   call set "_STRING=%%_STRING:!_FROM!=!_TO!%%
)

set _STRING
endlocal

例如:

E:\OS.ADMIN>LCASE.BAT The Quick Fox Jumps Over The Brown Fence.

结果:

_STRING=The Quick Fox Jumps Over The Brown Fence.
_STRING=the quick fox jumps over the brown fence.

7
不知何故,那个句子里应该包含字母 zy。也许是这句话:The Quick Brown Fox Jumps Over A Lazy Dog. - Jesse Chisholm

10
我找到了一个快速的谷歌搜索这个链接...
@echo off
goto :end_remarks
*************************************************************************************
*
*
*    authored:Sam Wofford
*    Returns lowercase of a string
*    12:13 PM 11/13/02
**************************************************************************************
:end_remarks
setlocal
set errorlevel=-1
if {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit
if {%1}=={/?} call :Help &goto :endit
call :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z

:start
set input=%1
set input=%input:"=%
set totparams=0
call :COUNT_PARAMS %input%
call :MAKE_LOWERCASE %input%
set errorlevel=
echo %convertedstring%
endlocal
goto :eof
:endit
echo %errorlevel%
endlocal
goto :eof

:MAKE_LOWERCASE
:nextstring
if {%1}=={} goto :eof
set string=%1
set /a params+=1
set STRINGCONVERTED=
set pos=0
:NEXT_CHAR
set onechar=%%string^:^~%pos%,1%%
for /f "tokens=1,2 delims==" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c
if not defined STRINGCONVERTED goto :NEXT_CHAR
shift /1
if %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end
goto :nextstring
goto :eof

:Help
echo USAGE:%~n0 string OR %~n0 "with spaces"
echo function returns the lowercase of the string or -1 (error)
echo strings with embedded spaces needs to be in quotes Ex. "lower case"
echo in a batch NTscript "for /f %%%%A in ('lcase STRING') do set var=%%%%A"
set errorlevel=
goto :eof

:checkit
set LCFOUND=
if /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof
set char=%1
for /f "tokens=2 delims=_=" %%A in ('set LCASE_') do call :findit %%A %char%
:skipit
if defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)
set /a pos+=1
goto :eof

:set_LCASE_array
:setit
if {%1}=={} goto :eof
set LCASE_%1_=%1
SHIFT /1
goto :setit

:findit
if defined LCFOUND goto :eof
set ucletter=%1
set lcchar=%2
if /i {%ucletter%}=={%lcchar%} set LCFOUND=yes
goto :eof

:COUNT_PARAMS
:COUNTPARAMS
if {%1}=={} goto :eof
set /a totparams+=1
shift /1
goto :COUNTPARAMS 

将其作为一个文件添加到您的路径中(小写.cmd),然后您就可以调用它,例如“Lowercase.cmd %Username%”,如果需要,您可以将其管道传递到另一个命令。

谢谢@Mauro :) 我将您发布的脚本保存为“LCase.CMD”,并调整第11行为..if not "%2"=="auto" setlocal然后将第24和24行调整为..if not "%2"=="auto" echo %convertedstring% if not "%2"=="auto" endlocal现在,我将其内联到自己的批处理文件中..if exist "LCase.cmd" ( set convertedstring= call LCase.cmd %uid% auto set uid=%convertedstring% ) - Rhak Kahr

8

当安装了脚本语言后,可以使用FOR来设置变量。

@FOR /F "delims=" %%s IN ('<<some script oneliner>>') DO @set MYVARIABLE=%%s

参考:关于 F 循环的资料

任何脚本语言都可以使用,只要它能将字符串转换为小写并输出结果。

以下是使用 Perl 5 的示例:

@FOR /F "delims=" %%s IN ('perl -e "print lc(pop)" %USERNAME%') DO @set USERNAME=%%s

使用 PowerShell 的示例:

@FOR /F "delims=" %%s IN ('powershell -command "$env:USERNAME.ToLower()"') DO @set USERNAME=%%s

现在,很有可能PowerShell已经默认安装了。


7

http://www.dzone.com/snippets/lowercasing-string-bat-files

lower.bat

echo>%1
dir /b/l %1>lower.tmp
set /p result=<lower.tmp
echo %result%

cmd

lower "Mein BinnenMajuskel"

结果

mein binnenmajuskel

注意:这是一种快速而不安全的变体。因为您需要创建两个文件,一个文件名与给定字符串相同,另一个名为lower.tmp,其中包含小写字符串。如果您在已存在此文件或目录的目录中执行lower "UserName"会发生什么?特别是在之后删除这些文件时...

改进版:

echo>%Temp%\%1
dir /b/l %Temp%\%1>%Temp%\lower.tmp
set /p result=<%Temp%\lower.tmp
del %Temp%\%1
del %Temp%\lower.tmp

可以简化为: echo>%username% && dir /b/l %username%>%username% && set /p USER=<%username% && del %username% - WPWoodJr

7

http://short.stop.home.att.net/freesoft/unix.htm下载一些适用于DOS的Unix实用程序,并使用tr.exe(字符转换)。

echo %USERNAME% | tr "[A-Z]" "[a-z]" 

我也使用一个名为4NT的DOS扩展命令替代工具,其中内置了@lower命令。

echo %@lower[%USERNAME%]

非常感谢您的评论。我考虑过那种方法,但那意味着必须在每个用户的计算机上安装那些工具,我希望能够使用现有的Windows工具来解决这个问题。 - Nano Taboada
没错。在某些时候,更好的解决方案是使用正确的工具,或者用你喜欢的编程语言编译这个简单的程序,并将其作为外部依赖提供给你自己的软件。 - Matthieu

7

这可能是在批处理文件中将字符串转换为小写的最快方法,因为它使用了,并且没有临时文件(它将生成的字符串保存在名为result的变量中):

@echo off

set LowerCaseMacro=for /L %%n in (1 1 2) do if %%n==2 (for %%# in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do set "result=!result:%%#=%%#!") else setlocal enableDelayedExpansion ^& set result=

set "string=SOme STrinG WiTH lowerCAse letterS and UPCase leTTErs"
%LowerCaseMacro%%string%

echo %result%

5
在我的批处理文件中,我正在将%USERNAME%与CSV文件进行比较。
如果用户使用大写字母登录,则程序将无法正常工作。
例如:
登录:GB2NOGU //不起作用
登录:gb2nogu // 起作用
在这里,我可以通过进行不区分大小写的比较来解决我的问题。
if /i %USERNAME%==gb2nogu (
     // Code here
)

参数 /i 告诉 cmd 进行不区分大小写的比较,因此它会忽略小写和大写字母之间的差异。

确实非常有用! - mfnx

3
:: UPcase.bat ==> Store in environment variable _UPcase_ the upper case of %1
:: -> Use quotes "" when the first argument has blanks or special characteres
::
:: Adapted from -> http://www.netikka.net/tsneti/info/tscmd039.htm
::
:: Note that the substitution method is case insensitive, which means that
:: while working for this application, it is not useful for all character
:: substitution tasks.
::
:: More concisely, one can capitalize (if you pardon the pun) on the fact
:: that in for and the substitution lower and upper case source are
:: equivalent.
@echo off

:: %~1 -> removes quotes from the first command line argument
:: http://steve-jansen.github.io/guides/windows-batch-scripting/part-2-variables.html
@echo off
::setlocal EnableExtensions
    :: echo %_UPcase_%
    call :ToUpcaseWithFor "%~1" _UPcase_
    :: echo %_UPcase_% _doit_1_
::endlocal & goto :EOF
goto :EOF
::
:: ======================
:ToUpcaseWithFor
setlocal EnableExtensions EnableDelayedExpansion
  set var_=%~1
  for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    set var_=!var_:%%c=%%c!
  )
endlocal & set %2=%var_%& goto :EOF

:EOF
:: UPcase.bat ==> EOF

0

这是相同的答案 /来自 @It Wasn't Me 这里


对于预测字符集,这个子字符串Set !var:A=a!是有效的,并且只能与/中的预定义子字符串一起使用。

对于这种类型的任务,为什么不借助来获得一些帮助呢?它可以使得处理非常规重音和辅音è, È, ä, Ä, ñ, Ñ, ç, Ç等成为可能。

/生成代码时,它将在运行时编译和执行....

这解决了可能出现的用户输入问题,其中序列带有重音符号,元音/辅音与传统的[a-z]和/或[A_Z]不同。


@echo off & setlocal EnableDelayedExpansion 

cd /d "%~dp0" && title <nul && title ...\%~dpnx0 /// !time:~0,8! !date!

if exist "%tmp%\ToUpLower.cs" 2>nul >nul del /q /f "%tmp%\ToUpLower.cs" 
set "_where=%__appdir__%where.exe" && set "_csc=%windir%\Microsoft.NET"
>"%temp%\ToUpLower.cs"  ( 
echo= using System; namespace SUQ1522019 ^{class Program ^{static void Main(string[] args^) ^{
echo= if (args.Length==2 ^&^& args[0].ToLower(^)=="-l"^) ^{Console.WriteLine(args[1].ToLower(^)^);^} 
echo= if (args.Length==2 ^&^& args[0].ToLower(^)=="-u"^) ^{Console.WriteLine(args[1].ToUpper(^)^);^}^}^}^}
)

set "_arg=/t:exe /out:"%tmp%\ToUpLower.exe" "%tmp%\ToUpLower.cs" /platform:anycpu "
for /f tokens^=* %%i in ('!_where! /r "!_csc!" "csc.exe"^|findstr /lic:"k\v2\." 
')do "%%~i" !_arg! /unsafe+ /w:0 /o /nologo

for /f tokens^=* %%U in ('"%tmp%\ToUpLower.exe" -u %USERNAME%')do set "_up_case=%%U"
for /f tokens^=* %%l in ('"%tmp%\ToUpLower.exe" -l %USERNAME%')do set "_low_case=%%l"

echo/  Your username upcase is: !_up_case!
echo/ Your username lowcase is: !_low_case!

echo/ >nul 2>nul copy "%tmp%\ToUpLower.exe" "." 
del /q /f "%tmp%\ToUpLower.*" >nul 2>nul && endlocal & goto :EOF

  • %USERNAME% 的输出结果
 Your username upcase is: USERNAME
Your username lowcase is: username

没有转义的ToUpLower.cs 代码:


 using System; namespace SUQ1522019 {class Program {static void Main(string[] args) {
 if (args.Length==2 && args[0].ToLower()=="-l") {Console.WriteLine(args[1].ToLower());} 
 if (args.Length==2 && args[0].ToLower()=="-u") {Console.WriteLine(args[1].ToUpper());}}}}

没有转义和缩进的ToUpLower.cs 代码:


using System
namespace SUQ1522019 
{
   class Program 
   {
      static void Main(string[] args)
      {
         if (args.Length==2 && args[0].ToLower()=="-l") 
         {
            Console.WriteLine(args[1].ToLower());
         } 

         if (args.Length==2 && args[0].ToLower()=="-u") 
         {
            Console.WriteLine(args[1].ToUpper());
         }
      }
   }
}

  • 这段代码已经在csc.exe的以下版本上编译/测试通过:
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe
c:\Windows\Microsoft.NET\Framework\v3.5\csc.exe
c:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe
c:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe
c:\Windows\Microsoft.NET\Framework64\v3.5\csc.exe
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe

以下是用于编译 代码的命令行
c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /t:exe /out:"%tmp%\ToUpLower.exe" "%tmp%\ToUpLower.cs" /platform:anycpu /unsafe+ /w:0 /o /nologo 

  • ToUpLower.exe 使用方法 将大写字母转换为小写字母
ToUpLower.exe -l STRING 

:: or ..

ToUpLower.exe -L STRING


  • ToUpLower.exe 使用方法 将小写转换为大写

ToUpLower.exe -u string

:: or ..

ToUpLower.exe -U string


为了保留ToUpLower.exe,请从copy命令中删除echo/


echo/ > nul 2> nul copy "%tmp%\ToUpLower.exe" "." 

这条命令行将从%temp%复制 ToUpLower.exe 文件到与你的批处理文件相同的文件夹中。


编程指南 C#:


抱歉我的英语有限


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接