How can i create one .bat file to delete the last carriage return in .csv file ?

I'm_me 0 Reputation points
2023-05-28T21:33:12.2733333+00:00

Hi everyone,

I'am writing one .bat file to delete the last carriage return in one .csv file. I didn't find it. Is anyone has an idea ?
Example :
blablabla [CR]
blablabla [CR]
blabla [CR] : CR to delete.

Thank you for your help.

Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
11,159 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Khaled Elsayed Mohamed 1,260 Reputation points
    2023-05-30T09:11:25.1533333+00:00

    HiTo delete the last carriage return (CR) in a CSV file using a .bat file (batch script), you can use a combination of commands available in Windows. Here's an example of how you can achieve this:

    1. Open a text editor (such as Notepad) and create a new file.
    2. Add the following commands to the file:
    
    @echo off
    setlocal enabledelayedexpansion
    
    set "inputFile=input.csv"
    set "outputFile=output.csv"
    
    REM Count the number of lines in the file
    for /f %%a in ('type "%inputFile%" ^| find /c /v ""') do set "totalLines=%%a"
    
    REM Read the input file and remove the last carriage return
    set "lineNumber=0"
    (for /f "delims=" %%b in (%inputFile%) do (
      set /a "lineNumber+=1"
      if !lineNumber! equ !totalLines! (
        echo|set /p=%%b
      ) else (
        echo %%b
      )
    )) > %outputFile%
    
    echo The last carriage return has been removed from the file.
    
    pause
    
    
    1. Customize the inputFile and outputFile variables according to your requirements. Set inputFile to the path of your CSV file and outputFile to the desired output file path.
    2. Save the file with a .bat extension (e.g., remove_last_carriage_return.bat).

    Make sure the .bat file is in the same directory as the input CSV file.

    When you run the .bat file, it will read the input CSV file, count the total number of lines, and remove the last carriage return (CR) from the file. The modified content will be saved in the specified output file. The original input file will not be modified.

    After running the script, you should see a message indicating that the last carriage return has been removed from the file. You can then check the output CSV file to verify the changes.

    Note: This script assumes that the CSV file uses Windows-style line endings (CR+LF). If your CSV file has different line endings, such as Unix-style (LF) or Mac-style (CR), you may need to modify the script accordingly.

    Remember to always test the script on a backup or sample file before applying it to important data to ensure it behaves as expected.

    0 comments No comments