/ / Como converter o valor de% USERNAME% para minúsculas em um script em lotes do Windows? - janelas, scripts, arquivos em lote, cmd

Como converter o valor de% USERNAME% em minúsculas em um script em lotes do Windows? - janelas, scripts, arquivos em lote, cmd

Eu estou automatizando algumas funcionalidades de software de controle de fonte usando um script de pontos, mas dado que nossos repositórios svn estão hospedados em uma caixa * NIX, eu estou enfrentando o eterno problema de caso entre esses dois mundos.

Existe alguma função cmd.exe para converter o valor da variável de sistema% USERNAME% do Windows para minúsculas?

Muito obrigado antecipadamente!

Respostas:

8 para resposta № 1

um rápido google encontrado esta...

@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

adicione isso como um arquivo (lowercase.cmd) ao seu caminho e você deve ser capaz de chamá-lo como "Lowercase.cmd% Username%", você poderia enviá-lo para outro comando, se necessário.


12 para resposta № 2

Bem, eu estava procurando por alguma sintaxe e tropecei nesta página. Eu sei que é velho, mas eu pensei em dar uma pausa e dar um chute no cérebro.

Aqui está algo um pouco mais curto e gerenciável. Isso apenas "força bruta" todas as letras maiúsculas para minúsculas sem considerar se a letra existe ou não na string. Assim, o loop funcional é executado exatamente 26 vezes, independentemente do tamanho da string.

Espero que isso ajude alguém.

@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

Exemplo:

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

Resultado:

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

3 para resposta № 3

baixar alguns utilitários unix para DOS http://short.stop.home.att.net/freesoft/unix.htm e use tr.exe (traduzir caracteres)

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

Eu também uso uma substituição de cmd estendido do DOS chamada 4NT que tem um comando incorporado @ menor

echo% @ lower [% USERNAME%]


2 para resposta № 4

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"

resultado

mein binnenmajuskel

CUIDADO: Variante rápida e suja, mas também insegura e perigosa. Porque você cria dois arquivos. Uma chamada como a corda dada e outro chamado lower.tmp, que contém a cadeia abaixada. O que acontece se você executar lower "UserName" em um diretório, onde este arquivo ou diretório já existe? Especialmente se você excluir esses arquivos depois ...


1 para resposta № 5

Quando uma linguagem de script é instalada, ela pode ser usada com um "FOR" para definir uma variável.
Qualquer linguagem que possa transformar e gerar uma entrada de string pode ser usada.

Um exemplo usando o Perl 5:

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

Um exemplo usando o PowerShell:

@FOR /F %%s IN ("powershell -command "(get-item env:"USERNAME").Value.ToLower()"") DO @set USERNAME=%%s

0 para a resposta № 6
:: 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