Edit text file using batch file - batch-file

I've searched a thousand of example and tried, but none of them actually works for me. My requirement is pretty straight forward, I have a file - config.txt, it has one of lines:
sqlServer=localhost
I'm trying to update this line to:
sqlServer=myMachine\sql2012
I looked examples online, some of them are just working with set variables, or some are not replacing but inserting. There are some examples are writing into a new file, but the new file has line number in front of each line. I don't find a useful instruction how to write batch scripts, and none of the update file batch scripts works for me.
It will be very helpful if you leave some comments.
Thanks in advance

EDITED - to adapt to comments
#echo off
setlocal enableextensions disabledelayedexpansion
set "config=.\config.txt"
set "dbServer=localhost\sql2012"
for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
) do for /f "tokens=1 delims== " %%a in ("%%~l"
) do if /i "%%~a"=="sqlServer" (
>>"%config%" echo(sqlServer=%dbServer%
) else (
>>"%config%" echo(%%l
)
type "%config%"
endlocal
Input file is read line by line (for /f %%l), then each line is split (for /f %%a) and if the first token in the line is "sqlserver" then the line is replaced, else the original line is sent to file.
The command used to retrieve the information in the first for loop includes an cd.>"%config%" that will remove the contents of the file, so the final resulting lines (that have been read in memory by the for command before removing them) are sent directly to the same file.

You can do this:
FINDSTR /I /V /B "sqlServer=" config.txt > config.new
ECHO sqlServer=myMachine\sql2012 >> config.new
DEL config.txt
REN config.new config.txt
The FINDSTR will remove all lines that start with sqlServer= and create a new file called newfile.
The ECHO will add a line at the end with sqlServer=MyMachine\sql2012.
The last two lines delete your existing config.txt and replace it with the output of the first two lines.

Related

Clear whitespace in text file using bat

I have the following batch file HERE
It searches for the line that contains...
[/Script/MyGame.Mode]
Then it creates a new line and adds...
RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
It works unless the original file contains spaces after each line. If there are no spaces it works perfect.
Is there an easy way to clear out all the spaces in the original file before it searches, copies and writes the new line in a new file?
Or is there a better way to do this overall. Sorry but I'm not knowledgeable at batch files yet. Thanks for any help given.
I figured it out. I was able to clear the spaces from the original file with the code below before running the copy and adding the new line.
I changed some file names then ran the code below before I'm checking the file and writing new line.
I had to show some code from my other bat to show you the file name changes. Once you combine everything together in one bat it works fine.
:CLEARWHITESPACE
for /F "eol=; tokens=1 delims=; " %%I in (Game.txt) do (
set /a count+=1
if !count! leq 10 echo %%I>>game.temp.txt
)
:SHOWLINE
set NewURL=RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
pause
:WRITENEW
set inputfile=game.temp.txt
set outputfile=game.temp2.txt
(for /f usebackq^ delims^=^ eol^= %%a in ("%inputfile%") do (
echo %%a
if "%%~a"=="[/Script/MyGame.Mode]" call echo %%NewURL%%
))>>"%outputfile%"

How to get just the first line of a text file written into a new text file using a batch file?

Okay I have several lines in a text file. I want to get the first line and save it in another file. For example this is the text file:
put returns between paragraphs
for linebreak add 2 spaces at end
for linebreak add 2 spaces at end2
for linebreak add 2 spaces at end3
I want put returns between paragraphs to be saved into another file.
I used
for /f "tokens=" %%A in ('findstr /r "^[0-9][0-9]*$" <"C:\Users\Sherlock\Desktop\AbcImport\123.txt"') do echo 123>>1234.txt
pause
But it doesn't work at all.
How to get just the first line of a text file written into a new text file using a batch file?
Option 1 - SET /P : This is the simplest and fastest pure batch solution, provided the line does not exceed 1021 bytes, and it does not end with control characters that must be preserved. The size of the file does not matter - it will always read and write the first line very quickly.
#echo off
setlocal enableDelayedExpansion
set "ln="
<"input.txt" set /p "ln="
>"output.txt" (echo(!ln!)
Option 2 - FOR /F : This will work with lines up to ~8191 bytes long, but it can be slow if the file is really large because the FOR /F loop must read the entire file before it processes the first line. This solution is basically the same as the Mofi answer, except it disables the EOL option, so it never ignores the first line, regardless what the first character is. It does have a limitation that it will skip empty lines, so technically it does not give the correct result if the first line is empty:
#echo off
for /f usebackq^ delims^=^ eol^= %%A in ("input.txt") do echo(%%A>"output.txt"&goto :break
:break
There is a way to preserve the first line if it is empty using pure batch, but I would not bother. I would move on to ...
Option 3 - JREPL.BAT, or some other non-batch solution : Batch is quite poor at manipulating text files. You are much better off using some other scripting language like VBScript, JScript, or Powershell. Or a Windows port of any number of unix utilities.
I would use JREPL.BAT - a hybrid JScrpit/batch regular expression text processing utility that runs natively on any Windows machine from XP onward. It is way overkill for such a simple task, but it is an extremely handy, powerful, and efficient tool to have in your arsenal. Once you have it, then it can be used for many text processing tasks. Full documentation is embedded within the script.
jrepl "^.*" "$&" /jendln "quit=true" /f "input.txt" /o "output.txt"
Use CALL JREPL if you put the command within a batch script.
Here is the batch code to write just first non blank/empty line of a text file into another text file.
#echo off
for /F "usebackq delims=" %%I in ("InputTextFile.txt") do (
echo %%I>"OutputTextFile.txt"
goto ContinueAfterLoop
)
:ContinueAfterLoop
InputTextFile.txt is the file in current directory containing the first line to copy.
OutputTextFile.txt is the file created in current directory with first line from input file copied into this output file.
The command GOTO is used to exit the loop after first line is processed and continue the batch file below the loop.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
goto /?
Read also the Microsoft article about Using Command Redirection Operators.
You can use use this command:
SetLocal EnableDelayedExpansion
for /f "tokens=* delims=;" %%m in ("C:\Users\Sherlock\Desktop\AbcImport\123.txt") do (
set /p FirstLine=<%%m
echo !FirstLine!>>1234.txt
)
and for multiple file:
SetLocal EnableDelayedExpansion
for %%a in ("*") do (
for /f "tokens=* delims=;" %%m in ("%%a") do (
set /p FirstLine=<%%m
echo !FirstLine!>>1234.txt
)
)
rem Get the first line of a text file:
set /P "line=" < "C:\Users\Sherlock\Desktop\AbcImport\123.txt"
rem Write it into a new text file:
echo %line%> 1234.txt

Batch scripting: find file and remove lines

I'm new to batch scripting and could use some assistance.
I'm trying to write a batch script that will open a .txt file, remove the first 4 lines, and delete some other things leaving just some numbers. I need some help deleting the first four lines.
#echo off
title test1
start users_6042014.txt
for /f "skip=4 delims=*" %%a in (C:\users_6042014.txt) do (
echo %%a >>C:\newfiletest.txt
)
xcopy C:\newfiletest.txt C:\users_6042014.txt /y
I thought this would delete the first lines and make a copy of the new file but it's not working. Any help would be greatly appreciated!
You don't tell us what isn't "working" about the batch.
The start users_6042014.txt will open the file with the default editor (presumably notepad) which is probably not what you want to do. Try commenting this line out, or remove it completely.
Note that
echo %%a >>C:\newfiletest.txt
will append to any existing C:\newfiletest.txt an probably also append a space to the end of each line.
Try
(for /f "skip=4 delims=*" %%a in (C:\users_6042014.txt) do echo %%a)>C:\newfiletest.txt
to create the file anew.
Finally, move in place of xcopy would replace the existing file; C:\newfiletest.txt would no longer exist.
Test this:
This will ignore lines starting with ; and blank lines.
#echo off
title test1
for /f "usebackq skip=4 delims=" %%a in ("C:\users_6042014.txt") do (
>>"C:\newfiletest.txt" echo %%a
)
move "C:\newfiletest.txt" "C:\users_6042014.txt"

Windows Command batch script to add filename to end of each row in a merged text file

I a new to windows command line scripts.
I have a batch file which i use to merge multiple text files into one. However i want to be able to also add the name of the text file the row comes from to the end of each row in the merged file.
This is the script i am currently working with:
#ECHO OFF
ECHO Creating %1...
FOR /F "usebackq tokens=1" %%G IN (`DIR /B "C:\My Documents\Data\*.txt"`) DO
(
ECHO Adding %%G
ECHO. >> Output.txt
TYPE %%G >> Output.txt
)
Now i know that to get the filename into the output file i need to use:
ECHO %%G >> Output.txt
However i'm not sure how i would add this to the current script so it adds the filename to each row and I have had no luck with finding any examples.
There is a simple two liner that works from the command line if you are willing to prefix each line with the file name instead of putting the file name at the end. This solution is extremely fast.
cd "C:\My Documents\Data"
findstr "^" *.txt >output.log
Each line will have the format of filename:line content
It is important that your output file use a different extension than the files you are merging. Otherwise you run the risk of the command processing its own output!
The other option is to make sure the output goes to a different folder, perhaps the parent folder:
cd "C:\My Documents\Data"
findstr "^" *.txt >..\output.txt
Or, if you are willing to include the full path to each file in your output, then make sure current directory is not the same as your source, and use
findstr "^" "C:\My Documents\Data\*.txt" >output.txt
The only drawback to the above solution is that problems can arise if the last line of a text file does not end with a newline character. This will cause the first line of the next file to be appended to the last line of the prior file. Something like: FILENAME1:last line without newlineFILENAME2:first line of next file
A simple script can append a newline to files that are missing the newline on the last line. Then the files can be safely merged with the filename prefix on each line:
#echo off
if "%~1" equ ":FindFiles" goto :FindFiles
cd "C:\My Documents\Data"
:: Append newline to text files that are missing newline on last line
for /f "eol=: delims=" %%F in ('"%~f0" :FindFiles') do echo(>>"%%F"
:: Merge the text files and prefix each line with file name
findstr "^" *.txt >output.log
exit /b
:FindFiles
setlocal enableDelayedExpansion
:: Define LF to contain a newline character
set lf=^
:: The above 2 blank lines are critical - do not remove
:: List files that are missing newline on last line
findstr /vm "!lf!" *.txt
You'll need to add each line in the file individually:
#ECHO OFF
ECHO Creating %1...
SET "sourcedir=c:\sourcedir"
FOR /F "delims=" %%G IN ('DIR /B /a-d "%sourcedir%\*.txt"') DO (
ECHO Adding %%G
ECHO. >> Output.txt
for /f "usebackq tokens=*" %%a in ("%sourcedir%\%%~G") do (
Echo %%a - %%G >> Output.txt
)
)
Note in the second last line, the file name and the line is seperated by a -, you can replace this with whatever (don't forget to check for escaping characters) or can get rid of this if you want.
I'm sure that will work, but if it doesn't, tell me the Error message and I can fix it for you.
Mona
---- [edit:pw]
Close - major problem was the ( on the FOR ... %%G line was on the line following the DO - must be on the same line as the DO.
Added /a-d to the DIR to prevent subdirectory names matching
changed "usebackq tokens=1" to use conventional quotes and allow spaces in filenames
assigned target directory name to sourcedir variable and included %sourcedir% in both FOR statements to allow execution from anywhere, otherwise the filenames found in C:\My Doc.... would be searched-for in the current directory for replication into the output.
OP needs to change value assigned to sourcedir to C:\My
Documents\Data

How to concatenate multiple lines of log file into single variable in batch file?

I have a log file containing a stack trace split over a number of lines. I need to read this file into a batch file and remove all of the lines breaks.
As a first step, I tried this:
if exist "%log_dir%\Log.log" (
for /F "tokens=*" %%a in ("%log_dir%\Log.log") do #echo %%a
)
My expectation was that this would echo out each line of the log file. I was then planning to concatenate these lines together and set that value in a variable.
However, this code doesn't do what I would expect. I have tried changing the value of the options for delims and tokens, but the only output I can get is the absolute path to the log file and nothing from the contents of this file.
How can I set a variable to be equal to the lines of text in a file with the line breaks removed?
If you want to use quotes for your filename in the FOR/F loop you need to add the usebackq option too, else you get a string not the content of your file.
for /F "usebackq delims=" %%a in ("%log_dir%\Log.log") do #echo %%a
Or remove the quotes
if exist "%log_dir%\Log.log" (
for /F "tokens=*" %%a in (%log_dir%\Log.log) do #echo %%a
)

Resources