2 Methods to Insert Text at Beginning of File on Windows

2 Methods to Insert Text at Beginning of File on Windows

When processing files via command line on Windows, may need to insert a text at the beginning of a file. This tutorial demonstrates how to do that on Windows.

Create a new file for testing:

(echo Line2& echo Line3& echo Line4) > test.txt

Method 1 - CMD

The following combination of commands allows to insert a text at the beginning of a file:

(echo Line1) > temp.txt & type test.txt >> temp.txt & move /y temp.txt test.txt >nul

A new line is added to temporary file. The echo command with parentheses prevents unwanted trailing space in first line. Content from old file is appended to temporary file which is renamed.

Method 2 - PowerShell

In PowerShell, use the following command to insert a text at the beginning of a file:

@("Line1") + (Get-Content test.txt) | Set-Content test.txt

A new line is combined with content of existing file and result is written to that file.

Leave a Comment

Cancel reply

Your email address will not be published.