Easiest way to add a text to the beginning of anot

2019-01-23 11:41发布

问题:

What is the easiest way to add a text to the beginning of another text file in Command Line (Windows)?

回答1:

echo "my line" > newFile.txt
type myOriginalFile.txt >> newFile.txt
type newFile.txt > myOriginalFile.txt

Untested. Double >> means 'append'



回答2:

Another variation on the theme.

(echo New Line 1) >file.txt.new
type file.txt >>file.txt.new
move /y file.txt.new file.txt

Advantages over other posted answers:

  • minimal number of steps
  • no temp file left over
  • parentheses prevents unwanted trailing space in first line
  • the move command "instantaneously" replaces the old version with the new
  • the original file remains unchanged until the last instant when it is replaced
  • the final content is only written once - potentially important if the file is huge.


回答3:

The following sequence will do what you want, adding the line "new first line" to the file.txt file.

ren file.txt temp.txt
echo.new first line>file.txt
type temp.txt >>file.txt
del temp.txt

Note the structure of the echo. "echo." allows you to put spaces at the beginning of the line if necessary and abutting the ">" redirection character ensures there's no trailing spaces (unless you want them, of course).



回答4:

The following will also work:

echo "my line" > newFile.txt
type newfile.txt myOriginalFile.txt > myOriginalFile.txt

In the first line you are writing my line into newfile.txt. In the second line you are replacing the text from myOriginalFile.txt by overwriting it with the text from newfile.txt and myOriginalFile.txt, creating a new myOriginalFile.txt that contains both.



回答5:

If the first part of the line can be sorted, such as date/time then use the SORT /R command to put the most recent entries at the top of the file. The following will place a date/time stamp in the form of "YYYY-MM-DD HH:DD:SS AM/PM" to the start of each line:

echo %DATE:~-4%-%DATE:~7,2%-%DATE:~4,2% %TIME% "my text line" >> myOriginalFile.txt
sort /R myOriginalFile.txt /O myOriginalFile.txt

However, as files grow very large this method (as well as the ones above) become slow. Consider sorting only when required instead of with each entry - or use another scripting/programming language