2015-11-03 29 views
0

對於如我的文本文件說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 
+0

看一看在http:但是你可以用一個小竅門寫不qoutes中引用的字符串// www.dostips.com/DtTipsStringManipulation.php#Snippets.TrimRightFOR – lit

+0

我是否應該在Call函數中進行任何更改?所以即使我介紹PIPE'|'符號,空格被刪除 – Balagi149

+0

嘗試使用'call:sub1「%%〜a」',然後在子程序中,設置'set'S =%*「'; – aschipfl

回答

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. 
) 
+0

請注意,一個字符串可能是8191個字符長(不僅僅是31個)... – aschipfl

0

你有一個問題:你的`call'參數必須被引用,所以有毒字符被保存。

當你從子程序回來時,還有第二個問題:從字符串中刪除引號會使得密碼字符再次變爲有毒。

@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您的需要(空格最大數量被刪除))

+0

謝謝Stephan。你的代碼工作得很好。但是我發現R2.txt中的空行沒有出現在R1.txt文件中。我怎麼能從這裏出來? – Balagi149

+0

你會向我解釋你的代碼嗎?所以我可以理解它是如何工作的 – Balagi149

+0

我注意到,在發佈我的答案後,您在R2.txt中用空行編輯了您的問題。我在此之後調整了我的答案,現在應該可以工作。 – Stephan

相關問題