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.

The 3 Comments Found

  1. Avatar
    Aureo Dantas Reply

    how to do this with several files? Because I executed the command with get content *.sql and set content *.sql and it took all the contents of all the files and put one in the others, so I had several files with their contents unified inside . I want to insert the characters in the first line of the files without having to name each file separately.

    i am using powershell

    • Avatar
      lindevs Reply

      To insert a text at the beginning of several files, you can use the following PowerShell script:

      foreach ($File in Get-ChildItem *.sql) {
          @("Line1") + (Get-Content $File.fullname) | Set-Content $File.fullname
      }
  2. Avatar
    Manish Reply

    thanks lindevs, this really helped me today, was looking for similar script to add a text at BOF.

    Thanks
    Manish

Leave a Comment

Cancel reply

Your email address will not be published.