Easiest way to add a text to the beginning of anot

2019-01-23 11:23发布

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

5条回答
闹够了就滚
2楼-- · 2019-01-23 11:48

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.

查看更多
劫难
3楼-- · 2019-01-23 11:54
echo "my line" > newFile.txt
type myOriginalFile.txt >> newFile.txt
type newFile.txt > myOriginalFile.txt

Untested. Double >> means 'append'

查看更多
仙女界的扛把子
4楼-- · 2019-01-23 11:58

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.
查看更多
狗以群分
5楼-- · 2019-01-23 11:58

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).

查看更多
家丑人穷心不美
6楼-- · 2019-01-23 12:06

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

查看更多
登录 后发表回答