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 2 Comments Found
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
To insert a text at the beginning of several files, you can use the following PowerShell script:
Leave a CommentCancel reply