Search code examples
batch-filedel

How to delete the last character of a file


I use this batch files to create a list of files

@echo off
(for /f "delims=" %%a in ('dir/b/a-d *.tex') do   echo %%a,)>liste.dat

the result is like this

file1.tex,
file2.tex,
file3.tex,
...
lastfile.tex,

how do I delete the last comma?


Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    set "comma="
    < NUL (
    for %%a in (*.tex) do (
       set /P "=!comma!%%a"
       set comma=,^
    %Empty line%
    )
    echo/
    ) > liste.dat
    

    EDIT: Reply to a comment

    Ops! When I was developing this code I just displayed the output in the screen, where it looks correct:

    C:\> test.bat
    One.tex,
    Three.tex,
    Two.tex
    

    Even if the output is sent to a file and the file is displayed in the screen, the output looks correct:

    C:\> test.bat > output.txt
    
    C:\> type output.txt
    One.tex,
    Three.tex,
    Two.tex
    

    However, the character inserted after each comma is just a LF so if this file is open with Notepad, the LF's are not converted to "end of lines"; just cmd.exe screen output converts LF to CR+LF pair ("cooked output" instead of "raw output").

    The way to fix this detail is inserting a complete CR+LF pair after each comma:

    @echo off
    setlocal EnableDelayedExpansion
    
    for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"
    
    set "comma="
    < NUL (
    for %%a in (*.tex) do (
       set /P "=!comma!%%a"
       set comma=,!CR!^
    %Empty line%
    )
    echo/
    ) > liste.dat