Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How would I edit a file from a .bat file that changes the contents of a file located somewhere on the hard drive.

For example there is a file on my desktop, can I make a .bat script that will add a line to the file like "hello" when it already had some content in it? I would like to add that "hello" line at the end of the file. Can it also edit a file that has no extension such as the HOSTS file?

share|improve this question

1 Answer 1

Adding a line to a file is easy using redirection.

echo Hello>>file

will append a line containing Hello to the end of file.

echo.>>file

inserts a blank line.

Be careful! The quite similar command

echo.>file

replaces the entire contents of file with a blank line. All previously stored information will be lost!

There's nothing special about files without extensions. However, the HOSTS file will be protected if UAC is enabled. Running the batch file as Administrator removes the protection.

share|improve this answer
    
even when i run the program as admin i still cant change anything in folders that are part of windows such as the hosts file... any reason why? also how to i put in new lines and tabs in the script? –  Megaeverything Mar 1 '13 at 0:53
    
Do you run the batch file as administrator or using an administrative account? There's a difference. You can use a literal tabulator in your batch file if you create it with, e.g., Notepad. As for newlines, just use several echo commands. –  sudo Mar 1 '13 at 1:01
    
yes i did right click on it and hit run as administrator and there is only one account on my computer (me) so i assume that it is adminstrator. –  Megaeverything Mar 1 '13 at 1:07
    
so i got it able to edit the file but how do i make it hit enter before putting in a line of text? say for the hosts file when i do "echo 0.0.0.0 randomwebsite.com >> %Windir%\System32\drivers\etc\hosts" it will put the text on the last line of whatever is already there. i want it to make a new line. how do i do that? –  Megaeverything Mar 1 '13 at 1:38
    
echo.>>file inserts a blank line. Btw, how did you do it? Remove read-only attribute? Take ownership? –  sudo Mar 1 '13 at 1:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.