从变量中删除尾随空格的 Bat 文件

问题描述 投票:0回答:1

我扩展了我原来的问题,因为我还需要用户输入月份并验证 1 到 12 之间的条目。

原始代码从文本字符串中删除了所有空格,但在测试时我发现我只需要从变量中删除尾随空格。

我已经尝试了网站上的各种代码,我可以在单独的bat文件中使用这些代码,但是当我将其放入现有代码中时,它不起作用。我认为这可能与延迟扩张有关,但我不确定。

这是我当前的代码:

@ECHO OFF
SETLOCAL
rem bat file to prompt for  month, read  name from within file and rename file to that name

rem  get month from user 1 to 12
set "Month="
set /P "Month=Please select month: 1 to 12 "
rem echo %Month%

if %Month% GEQ 1 if %Month% LEQ 12 goto :valid 

if %Month% LSS 1 if %Month% GEQ 13 goto :notvalid 

:notvalid
rem the entry is not valid
echo The number you entered is not valid please try again.
pause
exit

:valid
rem  The entry is valid proceed to renam



SET "sourcedir=D:\GH test files"
SET "filename1=%sourcedir%\test.TXT"
SET "newname="
FOR /f "usebackqskip=4delims=" %%e IN ("%filename1%") DO IF NOT DEFINED newname SET "newname=%%e"
SET "newname=%newname:~46,18%"


REM commented out next line as want to retain spaces within text but remove trailing
REM SET "newname=%newname: =%"

REM - new code added to remove trailing spaces
@echo off
setlocal EnableDelayedExpansion
set "newname=%x: =" & (if "!newname!" neq "" set "x2=!x2! !newname!") & set "newname=%" & set "x2=!x2:~1!"


pause


REN "%filename1%" "Sample_%newname%_Mth%Month%_.txt"


echo Your file has been renamed to "Sample_%newname%_Mth%Month%.txt" you can now close this window.

Pause

这些线路没有按预期工作:

@echo off
setlocal EnableDelayedExpansion
set "newname=%x: =" & (if "!newname!" neq "" set "x2=!x2! !newname!") & set "newname=%" & set "x2=!x2:~1!"

这是我的测试数据

1221424124124
141241214141414141xvvvvv24142141414
14214142141421
4114141414141
141241214141414141xvvvvv2414214141400000046976THISISTHETEXT       AXXXXXX

目前我的代码将我的文件重命名为

Sample_THISISTHETEXT     _Mth2_.txt
,但我需要它将其重命名为
Sample_THISISTHETEXT_Mth2_.txt
,即删除尾随空格。如果中间有空格,即这是我的文本,它应该保留它们。

batch-file
1个回答
0
投票

Aacini如何通过单个命令修剪前导和尾随空格?的答案中编写的代码仅在至少有一个尾随空格时才有效,否则此代码将从最后一个空格字符之后删除所有内容字符串值。它还删除了环境变量的字符串值内的连续空格。 aschipfl在答案下面的评论中提到,以及他对 Remove Trailing Spaces from a file using Windows Batch?

的回答

这是一个基于问题中的批处理文件的注释批处理文件,其中包含许多增强功能,以使其安全可靠。

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "UsePause="
rem Define the environment variable UsePause with a command line to execute
rem before existing processing of this batch file if the Windows Command
rem Processor was started with argument 0 being cmd and argument 1 being
rem case-insenstive the option /C as it is done one double clicking on a
rem batch file. The environment variable UsePause is not defined on batch
rem file being executed from within a command prompt window.
setlocal EnableDelayedExpansion & for /F "tokens=1,2" %%G in ("!CMDCMDLINE!") do @endlocal & if /I "%%~nG" == "cmd" if /I "%%~H" == "/c" set "UsePause=echo(& pause"
goto PromptMonth

:NotValid
echo The number you entered is not valid please try again.
echo(

rem Get month from user in the value range 1 to 12.
:PromptMonth
set "Month="
set /P "Month=Please enter a month [1-12]: " || goto PromptMonth
echo(
rem Remove all double quotes entered perhaps by mistake.
set "Month=%Month:"=%"
rem Prompt the user again on nothing else than " entered (by mistake).
if not defined Month goto NotValid
rem Verify if the entered string contains only ASCII digits
rem and prompt the user again if there is another character.
for /F delims^=0123456789^ eol^= %%I in ("%Month%") do goto NotValid
rem Remove all leading zeros for getting numbers like 08 and 09
rem interpreted as decimal numbers and not as invalid octal numbers. 
for /F "tokens=* delims=0" %%I in ("%Month%") do set "Month=%%I"
rem Prompt the user again on having entered just one or more 0.
if not defined Month goto NotValid
rem Prompt the user again on month value is greater than 12. It cannot
rem be negative and it cannot be zero anymore after the former checks.
if %Month% GTR 12 goto NotValid

rem The entered month value is valid. Proceed to rename.
set "FileName=D:\GH test files\test.TXT"
if exist "%FileName%" for /F "usebackq skip=4 eol=| delims=" %%I in ("%FileName%") do set "NewName=%%~I" & goto HaveNewName
echo ERROR: Failed reading the new name from: "%FileName%"& goto ErrorExit

:HaveNewName
rem Remove all " and check if the line consisted not only of double quotes.
set "NewName=%NewName:"=%"
if not defined NewName echo ERROR: Fifth line read from file is not of expected format.& goto ErrorExit
if "%NewName:~46%" == "" echo ERROR: Fifth line read from file is not of expected length.& goto ErrorExit
set "NewName=%NewName:~46,18%"

:RemoveSpaces
if not "%NewName:~-1%" == " " goto RenameFile
set "NewName=%NewName:~0,-1%" & if defined NewName goto RemoveSpaces
echo ERROR: New name is not of expected format as having only spaces.& goto ErrorExit

:RenameFile
set "NewName=Sample_%NewName%_Mth%Month%_.txt"
ren "%FileName%" "%NewName%" 2>nul
if not errorlevel 1 goto Success

echo ERROR: Failed to rename the file "%FileName%"
echo        to: "%NewName%"
:ErrorExit
%UsePause%
exit /B 1

:Success
echo Your file has been renamed to: "%NewName%"
if defined UsePause echo(& echo You can now close this window.
%UsePause%
endlocal

从固定宽度文件读取并分配给环境变量NewName的字符串中删除

尾随
空格是通过以下代码完成的:

:RemoveSpaces
if not "%NewName:~-1%" == " " goto RenameFile
set "NewName=%NewName:~0,-1%" & if defined NewName goto RemoveSpaces

这个程序并不明智。它检查新文件名字符串是否以空格字符结尾。如果不是这种情况,则不再有尾随空格,批处理文件的处理将在标签

RenameFile
下方继续。否则重新定义环境变量
NewName
,最后一个字符肯定是空格,从字符串值中删除。如果这不会导致环境变量
NewName
的删除,因为从一开始就只存在空格,则批处理文件的处理将再次继续上一行。如果必须删除数百或数千个尾随空格或批处理文件有数百行,则该代码将不好,因为
cmd.exe
必须逐行读取所有内容才能再次找到上面两行的标签
RemoveSpaces
,但是对于所描述的目的来说应该没问题。删除所有备注命令将有助于加快批处理文件和这个简单的 GOTO 循环的处理速度。

即使在文件的第五行,该代码也可以工作:

141241214141414141xvvvvv2414214141400000046976Dev & Test(!)100% AXXXXXX

要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。

  • echo /?
  • endlocal /?
  • exit /?
  • for /?
  • goto /?
  • if /?
  • pause /?
  • rem /?
  • ren /?
  • set /?
  • setlocal /?

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.