Batch File To Read And Modify Text File - file

Okay, so basically, I have a whole list of links in a plain text Notepad file, each link on a seperate line. All I am wanting to do is to add a bit of text before each link, specifically: 127.0.0.1 and a couple of spaces.
So this...
somelink.com
becomes this...
127.0.0.1 somelink.com
By now you've probably already guessed that I am trying to edit the contents of a text file to make it useable as a HOSTS file in Windows.
So I am wanting some batch file code, executable in a .bat file, which basically reads a Notepad text file, and then add "127.0.0.1 " at the beginning of each line with text on it. I am guessing this is probably a very simple piece of code for someone with some knowledge of MS DOS and batch file code, but that most certainly isn't me, and the only batch files I have ever written have been with help like now.
Thanks for any and all help in advance with this, it really is much appreciated.

read HELP FOR and then try this in a command prompt
FOR /F "delims=" %a in (input.txt) do #echo 127.0.0.1 %a >>output.txt
here is some explanation and some considerations to extend it with a little more complete functionality and put it in a BAT file
FOR is the command to iterate over the lines of your input text file. Read microsoft documentation at http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/for.mspx
input.txt is the text file that contains your list of domain names, it must reside in the current directory
output.txt will be the result file that will contain the list of domain names prefixed with 127.0.0.1, it will be created in the current directory
If you want to create a BAT file, you need to move the FOR command and edit it a little bit, changing the %a loop variable names to be %%a.
You can then place the BAT file either in the current directory, where your input resided and where the output will be created.
Alternativelly, you may place your BAT file, elsewhere. In that case, you need to invoke it with its full path.
Or you may even place it in a special directory (I have my own C:\Program Files\CMD) and add it in the PATH system variable. See here www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/path.mspx?mfr=true how you can change your PATH for your current session. And here ss64.com/nt/path.html you may find some explanation on how to make the PATH change permanent.
Also, you might be tempted to add some flexibility to your BAT file, instead of having constant input.txt and output.txt filename, replace them with %1 and %2 which represent the first and second command line parameters of your BAT file.
the user might then want to use files which contain blanks in their filenames. They might specify them surrounding the names with quotes ". In that case, you need to add some incantation usebackq in the FOR command for it to not break havoc when the user uses quotes.
Finally, you will need to decide what to do in case the output text file already exists, you migh want to consider prevent overwriting.
So putting all this pieces together, here is a short BAT file to get you started...
#echo off
if .%2==. goto help
if not exist %1 goto helpno1
if exist %2 goto helpalready2
FOR /F "usebackq delims=" %%a in (%1) do #echo 127.0.0.1 %%a >>%2
goto :eof
:help
echo you need to specify input and output text files
goto :eof
:helpno1
echo %1 not found
goto :eof
:helpalready2
echo %2 already exist
goto :eof
welcome to BAT programming and enjoy!

here we go!
(
Set /p line1=
Set /p line2=
Set /p line3=
Set /p line4=
)<Filename.txt
echo 127.0.0.1 %line1%>Filename.txt
echo 127.0.0.1 %line2%>>Filename.txt
echo 127.0.0.1 %line3%>>Filename.txt
echo 127.0.0.1 %line4%>>Filename.txt
This will Read the first four lines of the text file, and then put in your stuff and each line back into the line it came from.
Have Fun!

In addition to PA.'s answer, if you require a specific number of spaces, you can throw them into a variable and add it to the command as well.
SET spaces= # to the left is 10 spaces
FOR /F "delims=" %a in (input.txt) do #echo 127.0.0.1%spaces%%a>>output.txt
So the output will be
127.0.0.1 somelink.com
Batch-File flavor:
SET spaces= # to the left is 10 spaces
FOR /F "delims=" %%a in (input.txt) do #echo 127.0.0.1%spaces%%%a>>output.txt

Related

How do I change the directory that a batch file will output text to?

I am trying to write a log that a user will create in a batch file, as a small little game, but I can't seem to get the correct directory of the file down. I want to write to this directory:
BatchfileandFolder\subfolder1\subfolder2\ThedataisHere.txt
This is the code I have (I really don't know what I am doing)
Echo Write a piece of text here
set /p UserData=
>>\subfolder1\subfolder2\"ThedataisHere.txt" echo %UserData%
It is essential trying to dig deeper into the directory, but I don't know the exact command, and the help menu for CD, and PATH on the cmd.exe promt don't really help me that much.
Thank you for real human contact, speaking real English
#ECHO OFF
SETLOCAL
SET "logfile=u:\sub folder1\sub folder2\ThedataisHere.txt"
FOR /f "delims=" %%a IN ("%logfile%") DO MD "%%~dpa"
Echo Write a piece of text here
set /p UserData=
>>"%logfile%" echo %UserData%
GOTO :EOF
This method uses a variable logfile so that you aren't forever typing out the name (and avoid the pain if you want to change the names or directories, and the method allows you yo use multiple logfiles easily if you want)
I've deliberately used spaces in directory names to prove the method. The directory gets created immediately after the logfile name is set
append 2>nul to the md instruction line to suppress the directory already exists message
From there, simply use >>"%logfile%" to create the log. The quotes are not required if the filename doesn't contain separators like spaces.
Note that if the first character of the directory specified is \ then the directory is relative to the root, but if it is not then the directory is relative to the current directory on the destination drive. u: is a drive specifier, not a directoryname; I use u: as my test drive. Your choice is up to you.
If the directory structure already exists, it's pretty simple:
#echo off
set /p UserData=Write some text here:
#echo %UserData% >> "subfolder1\subfolder2\TheDataIsHere.txt"
If it doesn't exist already, you have to create it first (tested on Win7 64 bit):
#echo off
if not exist "subfolder1" md "subfolder1"
if not exist "subfolder1\subfolder2" md "subfolder1\subfolder2"
set /p UserData=Write some text here:
#echo %UserData% >> "subfolder1\subfolder2\TheDataIsHere.txt"
Although your description is ample, some important points are missing. It is obvious that you know "How to change the directory that a batch file will output text to", because you use the >> \subfolder\... notation, so this is not your problem. I can only guess that you want to know "How to get the directory where a batch file is located", so you can write to a log file placed two levels below that directory. If this is your problem, then you may use the %~P0 notation, that represent the path of the batch file; that is:
>> "%~P0subfolder1\subfolder2\ThedataisHere.txt" echo %UserData%
Note that the value returned by %~P0 ends in a backslash, so %~P0 must not be separated by an additional backslash from subfolder1; also note that the quotes must enclose the whole path of the file.
If this is not what you want, please carefully describe your real problem. Anyway, try to be clearer in future questions.

Batch read and rename from text file issue?

I'm a beginner with .bat files, and I'm attempting to rename multiple drawing (.dwg) files using a list generated in notepad. The notepad list contains a list of drawing numbers that look like this:
01013-13000p001
06301-12550p001
etc..
There is hundreds of them, and I want to take those numbers from the text and put it into a blank series of dwg files that are generic named for now (drawing.dwg, drawing(2).dwg, drawing(3).dwg etc..) I've only come up with a way to read a text file, but cant figure out how to take from the text file and rename multiple drawing files with it. Below is as far as I have gotten, after failed attempts of trying to take whats read from a text file and put it into the .dwg files. I plan on working this out in all the same directory, and any suggestions will be greatly appreciated. Thanks.
#echo off
for /f "tokens=* delims=" %%x in (dwgNumbers.txt.txt) do echo %%x
pause
would
for /f "delims=" %%x in (dwgNumbers.txt.txt) do echo copy /b "blank generic drawing.dwg" "%%x.dwg"
(as a batch line) do what you want? - note that the ECHO keyword is there to show what would be done. The echo keyword needs to be removed to actually execute the copy.
This will take the numbers from .txt, renaming the existing .dwg files with the data readed. If there are more files that numbers in .txt, it will rename until number exhaustion, no more.
for loop is using a dir command to get the list of files to avoid the case of files that after being renamed falls under the filter of the for and gets reprocessed.
This code has a echo command included in rename line to prevent data loss in case of malfunction. When the output to console is what is needed, remove the echo command from the rename line.
#echo off
rem Prepare environment
setlocal enableextensions enabledelayedexpansion
rem Read input file for numbers
< dwgNumbers.txt (
rem Process dwg files in directory
for /f "tokens=*" %%f in ('dir /b *.dwg') do (
rem Get number from input file
set "number="
set /p "number="
rem If there is a number, rename the file
if defined number echo ren "%%~f" "!number!.dwg"
)
)
rem Clean
endlocal

Batch script, copying filename to a txt file

Could anyone assist, i crate a batch script that will create bunch of txt files from the list i have, the txt then needs to contain a few lines on text and parts of it will need to have the name of a file.
So eg.
mkdir file1.txt
then the .txt file needs to have:
this file contains info
owner of the file is 'file.txt'
data for this file is in C:\Users\'file.txt'
Please let me know should this not be clear enough
Thanks
(copy/formatted from OP's comment - OP: Use the EDIT link to edit your question (judiciously, of course))
so far i have written
#echo off
for %%a in (*.txt) do type customer=customer fromAddress=email#domain.com andOrAddress=OR toAddress=email#domain.com outputPath=E:\Exgest\customer\email#domain.com outputFormat=MIME customHeaders=true fromDate=20030901 toDate=20101231 >> (*.txt)
This failed to add a text and only created *.txt file in this folder. Then I tried running
copy >> email#domain.com
for each email address in the list, and then
copy con >> name of each file
which just added syntax is correct to the txt file. Sorry guys, I am very new at batch scripting so.
If you want to write something in a file, then you need to write this in a batch file:
#ECHO OFF
ECHO.this file contains info>>file.txt
ECHO.owner of the file is 'file.txt'>>file.txt
ECHO.data for this file is in C:\Users\'file.txt'>>file.txt
Before ECHO. write what do you want to be sended to an file with any extension.
Before what do you want to write in that file, write > if you want to keep only a single line writed, and >> if you want to write more lines in that file.
So if you have:
ECHO.thing>>file.txt
ECHO.thing2>file.txt
file.txt will looks like this:
thing2
I hope that this helps you.
P.S.: Sorry for my bad english!
What you intend to do is unclear.
What your code seems to want to do is to append "customer=customer fr...01 toDate=20101231" to each existing .TXT file. The correct syntax for this would be
#echo off
for %%a in (*.txt) do ECHO customer=customer fromAddress=email#domain.com andOrAddress=OR toAddress=email#domain.com outputPath=E:\Exgest\customer\email#domain.com outputFormat=MIME customHeaders=true fromDate=20030901 toDate=20101231 >>"%%a"
which should add the extra line at the end of each .txt file.
Note the changes - ECHO not TYPE and >>"%%a" since the metavariable %%a will contain the filename of the files *.txt - and the "quotes" ensure that "filenames containing spaces.txt" are processed properly.
#user2782162 you need to edit your question and be more specific.
I've created the below batch based on what 'I think' you are trying to do.
Please let us know if this is what you want?
Also...i'm sure #Magoo could make this a lot simpler(you're a wiz at it).
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET listloc=list.txt
:start
FOR /f "tokens=* delims= " %%a IN (%listloc%) DO CALL :process1 %%a
ECHO.
ECHO List finished - Press any key to close.
PAUSE >nul
GOTO :eof
:process1
SET fname=%2
IF "%2"=="" GOTO :eof
:process2
ECHO %1=%2 >>%fname%.txt
SHIFT
SHIFT
IF NOT "%2"=="" GOTO process2
GOTO :eof
This is assuming that your input file 'list.txt' is arranged like the below...with all the info for each 'new file' on individual lines like this....
Contents of list.txt
customer=hello1 fromAddress=email1#domain.com andOrAddress=OR1 toAddress=email1#domain.com outputPath=E:\Exgest\customer\email#domain1.com outputFormat=MIME1 customHeaders=true1 fromDate=200309011 toDate=201012311
customer=hello2 fromAddress=email2#domain.com andOrAddress=OR2 toAddress=email2#domain.com outputPath=E:\Exgest\customer\email#domain2.com outputFormat=MIME2 customHeaders=true2 fromDate=200309012 toDate=201012312
customer=hello3 fromAddress=email3#domain.com andOrAddress=OR3 toAddress=email3#domain.com outputPath=E:\Exgest\customer\email#domain3.com outputFormat=MIME3 customHeaders=true3 fromDate=200309013 toDate=201012313
The Batch will read the 'list.txt' 1 row at a time.
It will use the value for "customer" on each row as the name for the new file.
Example below show what the output for the first row will look like..
Contents of hello1.txt
customer=hello1
fromAddress=email1#domain.com
andOrAddress=OR1
toAddress=email1#domain.com
outputPath=E:\Exgest\customer\email#domain1.com
outputFormat=MIME1
customHeaders=true1
fromDate=200309011
toDate=201012311

How to use a .txt file as an command

I am developing on a lot of batch programs that need to have a option, to do the work easy to the user. So he can type in the host, domain, IP address name in a text file, instead of editing 10 different batch files and 1/20 lines in one batch file.
I have an idea that might work if it gets a little push:
Command.txt
ping http:www.stackoverflow.com
ping1.bat
#echo off
Cd ..
Echo testing connection.
Type command.txt {please describe the solution here}
for /f "delims=" %%a in (file.txt) do "%%~a"
It sounds like you just want a configuration file that you can reference from your batch files. I do this by setting environment variables that are defined in an .ini file.
Config.ini
host=myhostname
domain=mydomain
ip=10.10.10.1
Then in your batch files, use the command:
for /f "delims== tokens=1,*" %%A in (config.ini) do #set %%A=%%B
From that point forward, you will have 3 variables that you can use: %host%, %domain%, and %ip%.

How to open a file using a string variable in path name in batch file

I have a text file, call it path.txt in C:\path.txt and it will only have one line of text at a time. That line of text will be a file path, call it C:\projects\test.txt.
What's the best way to first read the text from C:\path.txt and then second use the sort command in a batch file to alphabetize the file whose path is defined by the text string in path.txt ?
Lastly, I want to erase the line of text from that C:\path.txt file.
Please let me know if this is too vague or needs a better explanation and thanks in advance.
The batch file I have now reads:
FOR /F "tokens=*" %%i IN (C:\DONOTMODIFY.txt) DO #ECHO %%i
set "filename=%%i"
SORT filename /O filename
Why the artificial limitation of only one line? Anyway yes this is simple enough. Anyway this will process any number of lines in target.txt. Code off my head so test before real use.
#echo off
for /f %%i in (target.txt) do (
sort %%i /o %%i
)
echo. > target.txt
EDIT:
Instead of echo. > target.txt you could use copy /y nul target.txt > nul that actually creates a totally empty file unlike echo. that makes a blank line.
PS: a tip for future questions: Show that you actually tried something. This is not a do my program for you site.

Resources