Removing Trailing Whitespace in .txt file

21,020

Simply remove the extra space from your source ;)

@echo off
setlocal enabledelayedexpansion

for /F "tokens=*" %%A in (C:\test\Index.txt) do (
    set line=%%A
    echo(!line:~1!>>C:\test\Index1.txt
)

I also used echo( to guard against lines that become empty when you strip the first character. ECHO without anything following results in ECHO is off. message in your output.

Your simplistic script works fine in many cases. But it will have problems if your input contains ! character, or if you need to preserve blank lines. There are solutions for those issues, but the code becomes more complicated, and slower.

I use a hybrid JScript/batch utility called REPL.BAT whenever I want to modify contents of a file. It performs a regex search and replace on stdin and writes the result to stdout.

Assuming REPL.BAT is in your current directory, or better yet, somewhere within you PATH, then your script could be replaced with the following one liner that is both faster and more reliable:

type "C:\test\Index.txt"|repl "^." "" >"C:\test\Index1.txt"
Share:
21,020

Related videos on Youtube

Someone in VA
Author by

Someone in VA

Updated on September 18, 2022

Comments

  • Someone in VA
    Someone in VA almost 2 years

    How do I remove a trailing whitespace on each line in a .txt file in following command? I created script below to remove 1st character in each line but this creates a whitespace at the end of each line...

    @echo off
    
    setlocal enabledelayedexpansion
    
    for /F "tokens=*" %%A in (C:\test\Index.txt) do (
        set line=%%A
        echo !line:~1! >> C:\test\Index1.txt
    )
    
    • nerdwaller
      nerdwaller almost 11 years
      Fixed your formatting, please make sure that it still looks as expected.