Samraan
Samraan

Reputation: 285

How to remove extra comma from line in text file in batch file?

I'm trying to remove extra comma from end of the line in text file. Below is my approach:

set "n=%~,"
for %%t in (*.txt) do (
findstr /v /r /c:"$[%n%]*$" > res.txt
)

But it's no replacing the extra comma from text file. The content of text file as follows:

abc,asd,123,
1234,prq,456,,,,,
jkl,abc,9876,,,
5679,3459,gjh,,

I want the expected output as follows:

abc,asd,123
123,prq,456
jkl,abc,9878
5679,3459,gjh

Upvotes: 2

Views: 3632

Answers (2)

Dale
Dale

Reputation: 1901

I think substring will help you to get it done:

@echo off
setlocal EnableDelayedExpansion

for %%a in (*.txt) do (
    set txtPath=%%~fa
    echo !txtPath!
    for /f %%b in ('type "!txtPath!"') do (
        set line=%%b
        set output=!line!
        if "!line:~-1!"=="," (
            for /l %%i in (1,1,1000) do if "!output:~-1!"=="," set output=!output:~0,-1!
        )
        echo !output!>> res.txt
    )
)

As shown in the code above, It will help to trim up to 1,000 unwanted trailing comma and place the formatted output to a text file. You may refer to this link for more information about string manipulation in batch. Hope it helps.

Upvotes: 1

foxidrive
foxidrive

Reputation: 41224

This uses a helper batch file called repl.bat from - https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

@echo off
for %%t in (*.txt) do (
   type "%%t" |repl ",*$" "" >> res.tmp
)
ren res.tmp res.txt

Upvotes: 2

Related Questions