Steve333
Steve333

Reputation:

Windows: in batch file, write multiple lines to text file?

How can I do the following in a Windows batch file?

  1. Write to a file called subdir/localsettings.py
  2. Overwrite all existing content...
  3. ...with multiple lines of text...
  4. ...including a string that is "[current working directory]/subdir" (which I think might be %cd%/subdir?)

Please note, I want to do this as part of a batch script so I can't use con + Enter (at least, maybe I can, but I don't know how to simulate Enter as part of a batch script).

Thanks!

Upvotes: 36

Views: 106496

Answers (3)

Dorian Grv
Dorian Grv

Reputation: 499

If you wann do it in 1 line, here a more complex example

  • I simulate a carriage return with \n
  • I escape special character for parenthesis
  • I replace the \n with what is needed in batch
set text=Cols:\n- Port de Lers (1517m) avec le col d'Agnès (1570m)\n- Col de la Core (1395m)\n- Col de Menté (1349m)\n- Col de Peyresourde (1569m)\n- Col du Tourmalet (2115m)\n- Col d'Aubisque (1709m)\n- Col de Marie-Blanque (1035m)\n- Col de Labays (1354m)
set "text=%text:(=^(%" :: I escape special character for parenthesis
set "text=%text:)=^)%" :: I escape special character for parenthesis
set "text=%text:\n= >> temp.txt & echo %" :: I replace the `\n` with what is needed in batch 
set "text=%text:"=%"
if exist "temp.txt" rm temp.txt :: just remove the file if exist to avoid to append in it
echo %text% >> temp.txt
cat temp.txt :: print result
C:\ > cat temp.txt
Cols:
- Port de Lers (1517m) avec le col d'Agnès (1570m)
- Col de la Core (1395m)
- Col de Menté (1349m)
- Col de Peyresourde (1569m)
- Col du Tourmalet (2115m)
- Col d'Aubisque (1709m)
- Col de Marie-Blanque (1035m)
- Col de Labays (1354m)

If you wanna delete the last \r\n use truncate -s -2 temp.txt Install git on windows to be able to use truncate

Upvotes: -1

access_granted
access_granted

Reputation: 1907

echo Line 1^

Line 2^

Line 3 >textfile.txt

Note the double new-lines to force the output:

Line1
Line2
Line3

Also:

(echo Line 1^

Line 2^

Line 3)>textfile.txt

Upvotes: 8

grawity_u1686
grawity_u1686

Reputation: 16147

Use output redirection > and >>

echo one>%file%
echo two>>%file%
echo three>>%file%

Or in a more readable way: (In cmd.exe, using "echo one >%file%" would include the whitespace before >.)

>%file%  echo one
>>%file% echo two
>>%file% echo three

You could also use:

(
    echo one
    echo two
    echo three
) >%file%

Upvotes: 66

Related Questions