Search code examples
batch-filenewlineforfiles

Remove last new line character of text file in batch


I have a directory with nany text files, each containing an URL. I want to write each URL including a new line character to a text file. Therefore I created two batch files:

job.bat:

@echo off
forfiles /m *.m3u /c "cmd /c output.bat @file"

output.bat:

@echo off
type %1 >> urls.txt
echo. >> urls.txt

When I run job.bat all URLs are written to the text file.

But there is one problem: At the end of the text file there will be a new line at the end of the text file, even if no further line will follow. What can I do to remove the new line character at the end of urls.txt?

urls.txt should look like this: urls.txt

That's how job2.bat looks like: job2bat

I'm not able to insert a screenshot of urls.txt, since it needs to be scrolled. But I can tell you, that it contains all URLS, one after another without being seperated by any space or new line character.

The exact .m3u files can be found on a subpage of the homepage of a German radio station (ending with .m3u). Therefore I do not include any screenshot of a m3u file.


Solution

  • If you have just a few files, (limited by the string length of the urls with regards maximum size of the variable environment), and your urls do not contain ! characters, (which would be deleted), you may get away with something like this:

    @Echo Off & SetLocal EnableExtensions EnableDelayedExpansion
    For /F %%G In ('Copy /Z "%~f0" NUL') Do Set "cr=%%G" & (Set lf=^
    % 0x0A %
    )
    Set "fl=" & For /F Delims^=^ EOL^= %%G In ('Type *.m3u') Do If Not Defined fl (
        Set "fl=%%G") Else Set "fl=!fl! %%G"
    If Defined fl Set /P "=%fl: =!cr!!lf!%" 0<NUL 1> "urls.txt"
    

    If your files do not contain line terminators or line endings, which I've determined, seems to be consistent, you could just replace a different character or sequence of characters instead:

    @Echo Off & SetLocal EnableExtensions EnableDelayedExpansion
    For /F %%G In ('Copy /Z "%~f0" NUL') Do Set "cr=%%G" & (Set lf=^
    % 0x0A %
    )
    Set "fl=" & For /F Delims^=^ EOL^= %%G In ('Type *.m3u') Do Set "fl=%%G"
    If Defined fl Set /P "=%fl:3http:=3!cr!!lf!http:%" 0<NUL 1> "urls.txt"