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"
Related
I have a file MyFile.ini with a section in it [MySection]
I want to add a new line with a return after it under that section, via a batch file.
Here's the batch file I last tried:
#echo off
Set file=MyFile.ini
Set section=[MySection]
Set newline=MyNewValue=MyNewSetting
for /f "tokens=*" %%l in (%file%) do (
(echo %%l)>> "%file%"
if /i "%%l"=="%section%" (
(echo %newline%)>> "%file%"
)
)
exit
The above has no effect on the ini file.
I want the ini file to go from this:
[MySection]
SomeExistingValue=SomeExistingSetting
To this:
[MySection]
SomeExistingValue=SomeExistingSetting
MyNewValue=MyNewSetting
Any answer will be greatly appreciated because once I can figure this out I can replicate it and add several settings to my file, it's all a bit tedious doing it manually, especially when I do the exact same thing to the exact same file, every time. The file name never changes, the section always exists, the setting I am adding never exists, so all that stuff does not need to be accounted for, nor does making a backup of the file, I can just unzip my backed up file if it gets messed up.
Here's an example based upon my commented methodology:
#Echo Off
Set "file=MyFile.ini"
Set "section=[MySection]"
Set "newline=MyNewValue=MyNewSetting"
Copy /Y "%file%" "%file%.bak">NUL 2>&1||Exit /B 1
(For /F "Tokens=1*Delims=]" %%G In (
'^""%__AppDir__%find.exe" /N /V ""^<"%file%.bak"^"'
)Do If /I "%%H"=="%section%" (Echo=%%H
Echo %newline%)Else Echo=%%H)>"%file%"
Rem Del "%file%.bak"
I have Remarked the last line, because I think it's more important to ensure that the resultant file, %file%, is correct, before you Delete the original, %file%.bak. The choice to do so ultimately lies with yourself.
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%"
I have hundreds of csv files . csv files are stored in folders and sub folders . I want to search fifty csv file whose file names have been determined , for example 1.csv , 2.csv , 3.csv , ... , 50.csv . very troublesome if I searched one by one using the Windows search tool . I would like if the files are found , save in the folder named FOUND . please help to overcome this problem by using the batch programming / bat ? thank you very much
There's a number of approaches one can take, depending on how much automation you require... To help you get started, you may want to look at this it helped me (and indeed continues to do so) when I started learning batch. Furthermore I will provide one possible template for achieving your objective, as I have interpreted it. Perhaps it is not the most elegant or efficient method, but it introduces a number of batch commands that you may or may not have encountered, which in turn may help you develop your own method.
#echo off
setlocal enabledelayedexpansion
echo Please enter a drive letter:
set /p "drive=>"
echo Please enter a search string:
set /p "searchstring=>"
echo %searchstring%>search.txt
set /p search=<search.txt
set /a suffix=0
echo.>>search.txt
:LOOP
for /f "tokens=*" %%i in ("search.txt") do (
set /a suffix=suffix+1
set seq=%search% !suffix!
echo !seq!>>search.txt
)
if !suffix! leq 49 goto LOOP
for /f "tokens=*" %%i in (search.txt) do (
for /f "tokens=*" %%j in ('dir /b /s /a-d %drive%:\"%%i.csv" 2^>nul') do (
if not exist "%~dp0\found" md "%~dp0\found"
move /y "%%j" "%~dp0\found\%%~nxj"
)
)
pause
This is not intended as a definitive solution, though you may find it answers your original query/request. All the best.
Here's another working solution for you..
#ECHO OFF
SETLOCAL EnableDelayedExpansion
REM First Set your directories input and output
SET InputDir=C:\Directory to your CSV files\
SET OutputDir=C:\Directory to your CSV files\FOUND
REM check if the FOUND directory exist, if not, then create it.
IF NOT EXIST OutputDir (
mkdir %OutputDir%
)
REM Grab a scan of the input directory and save it to a temporary file list.
Dir /a /b %InputDir%>"%OutputDir%\Found.txt"
REM Set the files you would like to find.
SET "File1=1.csv"
SET "File2=2.csv"
SET "File3=50.csv"
REM The loop, to process the matching file(s).
FOR %%A IN (%File1%,%File2%,%File3%) DO (
FOR /F "usebackq" %%B IN ("%OutputDir%\Found.txt") DO (
IF %%A==%%B (
copy "%InputDir%\%%A" "%OutputDir%\%%A"
)
)
)
REM Clean up the temp file list.
DEL "%OutputDir%\Found.txt"
Make note, I didn't add quotes to the Input and Output variables, but instead added quotes to the copy portion of the code to compensate for white spaces in your directory path. I tried to keep it simple, so you could follow the logic of how it processed what you are looking for, you can now modify this to your liking.. Have fun. Cheers!
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.
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