Jerin Thenayan
Jerin Thenayan

Reputation: 21

How to insert line breaks on existing text file?

I have an existing text file that is one long string. I would like to create a .bat script to insert a carriage return and line-feed after it finds ~.

For example, the original text file is:

This is a long string~which should be many lines~and yet it is not

The wanted output is:

This is a long string~
which should be many lines~
and yet it is not

Upvotes: 2

Views: 20998

Answers (3)

Mofi
Mofi

Reputation: 49216

First let me explain the three different types of line break/newline/line ending/line termination types.

There is carriage return with the escape sequence \r with hexadecimal code value 0D abbreviated with CR and line-feed with the escape sequence \n with hexadecimal code value 0A abbreviated with LF.

  • Text files on MS-DOS/Windows use CR+LF as newline.
  • Text files on Unix/Linux/MAC (since OS X) use just LF as newline.
  • Text files on MAC before OS X use just CR as newline.

So I suppose in real the task is to insert after tilde not just a carriage return, but a carriage return + line-feed.

The answers on How can you find and replace text in a file using the Windows command-line environment? offer many solutions for replacing strings in text files using Windows command line.

The first suggested solution is with using JREPL.BAT written by Dave Benham.

jrepl.bat "~" "~\r\n" /X /F "FileToModify.txt" /O -

This solution works for a text file containing the posted line and produce the expected output.

Upvotes: 1

Compo
Compo

Reputation: 38719

I suppose you could also utilise PowerShell from your batch file too:

@If "%~1"=="" (Exit/B) Else If Not Exist "%~1" Exit/B
@Powershell -C "(GC '%~1') -Replace '~',\"`r`n\"|SC '%~1'"

The above accepts your input file as its argument, which means it could be as simple as a drag and drop job. The output file will be ASCII encoded by default.

Upvotes: 1

Squashman
Squashman

Reputation: 14340

I am not really sure how to do tilde replacement within a batch file because the tilde is a special character within the SET command for substrings.

But this should get you headed in the right direction.

@echo off
set "longline=This is a long string~which should be many lines~and yet it is not"

set count=1
:loop
FOR /F "tokens=1* delims=~" %%G IN ("%longline%") DO (
    SET "line%count%=%%G"
    set "longline=%%H"
    IF DEFINED longline (set /a count+=1 &goto loop)
)

FOR /L %%I IN (1,1,%count%) DO call echo %%line%%I%%

pause

Upvotes: 1

Related Questions