Philip
Philip

Reputation: 499

How to add a line break inbetween each lines in text file?

I am running a batch script to make a lines in text files with line breaks. This is for a testing & learning purpose.

I have a text file named file.txt which contains,

this is line one
this is line two
this is line three

I am running the batch script with code,

type file.txt >> output.txt
echo >> output.txt
type file.txt >> output.txt

Expected output.txt,

this is line one

this is line two

this is line three

But, actual output am getting in output.txt,

this is line one
this is line two
this is line three
(Empty line here)

All I need is a line break inbetween each lines. Any help will be appreciated a lot.

Upvotes: 0

Views: 1992

Answers (1)

aschipfl
aschipfl

Reputation: 34989

The redirection operator >> appends data to the redirection target (the file output.txt in your situation), but it cannot insert anything into them.

To accomplish your goal you need to read your input file file.txt line by line. This can be done by a for /F loop, like this:

rem // Write to output file:
> "output.txt" (
    rem // Read input file line by line; empty lines and lines beginning with `;` are skipped:
    for /F "usebackq delims=" %%L in ("file.txt") do @(
        rem // Return current line:
        echo(%%L
        rem // Return a line-break:
        echo/
    )
)

This appends another line-break and so an empty line at the end. If you want to avoid that, you could use a variable, like this:

rem // Reset flag variable:
set "FLAG="
rem // Write to output file:
> "output.txt" (
    rem // Read input file line by line; empty lines and lines beginning with `;` are skipped:
    for /F "usebackq delims=" %%L in ("file.txt") do @(
        rem // Do not return line-break before first line:
        if defined FLAG echo/
        rem // Return current line:
        echo(%%L
        rem // Set flag variable to precede every following line by a line-break:
        set "FLAG=#"
    )
)

Upvotes: 2

Related Questions