批处理脚本,用于删除每行的文本文件中的尾随空格

时间:2015-11-03 13:39:23

标签: batch-file

对于Eg我的文本文件说R2.txt具有以下文本:

Hai My name is Ragaaav SPACE SPACE SPACE
I am 22 yrs old SPACE SPACE SPACE SPACE

$ % ^&*() |||| SPACE SPACE

以下代码适用于前两行。但是,如果我介绍管道符号' |'在任何一行中空间都没有移除。相反,我发现重复包含PIPE符号的行。

@echo off > R1.txt & setLocal enableDELAYedeXpansioN
for /f "tokens=* delims= " %%a in (R2.txt) do (
call :sub1 %%a
>> R1.txt echo.!S!
)

goto :eof

:sub1
set S=%*
goto :eof

2 个答案:

答案 0 :(得分:2)

一点SET / P技巧应该有用。

编辑:抱歉忘了装饰部分了。 如果您需要从末尾删除超过31个空格,请将31更改为更大的数字。

编辑:输入已更改,因此必须更改代码以允许空行。

@echo off > R1.txt & setLocal enableDELAYedeXpansioN
for /f "tokens=1* delims=]" %%a in ('find /N /V "" ^<R2.txt') do (
    SET "str=%%b"
    for /l %%i in (1,1,31) do if "!str:~-1!"==" " set "str=!str:~0,-1!"
    >>R1.txt SET /P "l=!str!"<nul
    >>R1.txt echo.
)

答案 1 :(得分:1)

你有一个问题:你的`call'参数必须被引用,所以毒药字符会被保存。

当你从子程序回来时,你有第二个问题:从字符串中删除引号会使poision字符再次有毒。但是你可以用一个小技巧来编写没有qoutes的带引号的字符串:

@echo off 
REM create empty file:
break>R1.txt
setlocal enabledelayedexpansion
REM prevent empty lines by adding line numbers (find /v /n "")
REM parse the file, taking the second token (*, %%b) with delimiters
REM ] (to eliminate line numbers) and space (to eliminate leading spaces)
for /f "tokens=1,* delims=] " %%a in ('find /v /n "" ^<R2.txt') do (
  call :sub1 "%%b"
  REM write the string without quotes:
  REM removing the qoutes from the string would make the special chars poisonous again
  >>R1.txt echo(!s:"=!
)

REM Show the written file:
type r1.txt 
goto :eof

:sub1
set S=%*
REM do 10 times (adapt to your Needs):
for /l %%i in (1,1,10) do (
  REM replace "space qoute" with "quote" (= removing the last space
  set S=!S: "="!
)
goto :eof

(根据您的需要调整10(要移除的最大空格数))

相关问题