Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
)
share|improve this question
    
Fixed your formatting, please make sure that it still looks as expected. –  nerdwaller Sep 5 '13 at 18:55

2 Answers 2

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|improve this answer

you can use sed for Windows:

sed "s/\s*$//" infile.txt>outfile.txt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.