Find and check if negative write - find

i'm creating a batch file and just a little thing i want to know:
my (WINDOWS) batch file needs to search 'hello' in a text file.
If it is there, it should use the GOTO command to somewhere else in the batch file.
If it isn't there, it should write 'hello' on a new line.
How can you do that?
I know that you can use FIND and ERRORLEVEL, but i don't know how.

If you are using windows batchfiles, check if you can use helpers like the Unxtools. They are adding a lot of functionality.
Then you can use a grep and check the errorlevel (return value) ...
EDIT:
Here is some code to give you an idea:
find /i /c "hello" file.txt
if %errorlevel% equ 0 goto :found
echo hello

This may not be the most helpful answer... but, does it have to be a batch file? It sounds like Perl might be a better fit for what you are trying to do.

Try this one
echo off
find /c "hello" myfile.txt > nul
if errorlevel 1 goto notfound
echo hello
:notfound

Related

How to write STDOUT/STDIN via RedMon/cmd.exe to file?

I am trying to redirect a PS output to a file and process it further.
For this I am using the Printer Port Redirection RedMon which is sending the output to CMD.exe
C:\Windows\system32\cmd.exe
As arguments I expected that something like the following should work, but it does not. "%1" contains the user input for filename.
/c >"%1"
or
/c 1>"%1"
or
/c |"%1"
or
/c > "%1" 2>&1
What almost works if I send the output to a batch file which writes it then to file.
/c WriteOutput.bat "%1"
However, the batch file is somehow altering the file (skipping empty lines, and ignoring exclamation marks and so on...)
If possible I want to avoid a batch file. Is there a way to get it "directly" to a file?
Select "Print to FILE" in the printer options is not an option for me. I want the same end result but via cmd.exe being able to process it further.
Any ideas?
Edit:
Well, that's the batch file I used. It neglects empty lines and space at the beginning.
#echo off
setlocal
set FileName=%1
echo(>%FileName%.ps
for /F "tokens=*" %%A in ('more') do (
echo %%A>>%FileName%.ps
)
Well, so far I still haven't found a direct way to write STDIN via RedMon via CMD.exe to a file. As #aschipfl wrote, all the versions with for /F will skip lines and ignore certain characters.
However, with the following batch script (via RedMon) I end up with a "correct looking" file on disk.
C:\Windows\system32\cmd.exe /c WritePS.bat "%1"
"%1" contains the user input for filename without extension.
The Batch-File WritePS.bat looks as simple as this:
#echo off & setlocal
set FileName=%1.ps
more > "%FileName%"
However,
the resulting Postscript file is different from a file which I "Print to FILE" via the Postscript-Printer setup. I am pretty sure that all the printer settings which I can set are the same in both cases.
If anybody has an idea why there might be a difference, please let me know.

Batch Code to Skip Script if File is too Old

My Problem
As there are a ton of threads that address 'using a batch file to return file modify date' (or delete files older than, etc) - let me first specify my issue.
I'm looking to create a batch (not PowerShell, etc) that will return the last modify date of a specific file given UNC path and filename.
Code, Attempt 1
I've taken a peek at a few potential solutions on other threads, but I've run into a number of unique issues. The first and most obvious solution for this would be the "ForFiles" command in batch. For example:
set myPath=\\myUNCpath
set myFile=myFileName.csv
forfiles /p "%myPath%" /m %myFile% /c "GoTo OldFile" /d -6
Thus, if the file is older than I want -- jump to a specific section of my batch for that. However, this yields the error:
ERROR: UNC paths (\machine\share) are not supported.
However, this cmd won't work due to the use of UNC (which is critical as this batch is called by system's task scheduler). So it seems like the 'ForFiles' cmd is out.
Code, Attempt 2
I could go a more round about way of doing it, but simply retrieving the last modified date of the file (which in batch would return a string). I can truncate the string to the necessary date values, convert to a date, and then compare to current date. To do that, I've also looked into just using a for loop such as:
set myFile=\\myUNCpath\myFileName.csv
echo %myFile%
pause
FOR %%f IN (%myFile%) DO SET myFileDate=%%~tf
echo %myFileDate%
pause
Though my first debug echo provides the proper full file name, my second debug just returns ECHO is off., which tells me it's either not finding the file or the for loop isn't returning the file date. Not sure why.
I've also tried minor changes to this just to double check environmental variable syntax:
FOR %%f IN (%myFile%) DO SET myFileDate=%%~ta
Returns %ta
And finally:
FOR %%f IN (%myFile%) DO SET myFileDate=%~ta
Which without the extra '%', just crashes the batch.
I'm really at a loss at this point. So any tips or guidance would be greatly appreciated!
Using forfiles to a UNC path can be used using PushD
For just echoing the file older than x in UNC path, simply just use
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file
) & PopD
Here is one way how to use goto if file older than x found in UNC path using your examples.
if not exist "C:\temp" mkdir C:\temp
if not exist "C:\temp\test.txt" echo.>"c:\temp\test.txt"
break>"c:\temp\test.txt"
set myPath=\\myUNCpath
set myFile=myFileName.csv
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file >> c:\temp\test.txt"
) & PopD
for /f %%i in ("C:\temp\test.txt") do set size=%%~zi
if %size% gtr 0 goto next
:next
Huge thanks to both #Squashman and #MadsTheMan for the help. Luckily this batch finally is the piece of code that I can take to my boss to push switching over to at least using PowerShell!
Anyway, for those of you looking for the best way to get a UNC path file's modify date, here is what I've come up with. Not very different than other threads (and a thanks goes out to Squashman for spotting my missing " " in the for loop).
set myFile=\\myUNCpath\myFileName.ext
FOR %%f IN ("%myFile%") DO SET myFileDate=%%~tf
::And if you'd like to try to do long winded calculations you can further break the dates down via...
set fileMonth=%myFileDate:~0,2%
set fileDay=%myFileDate:~3,2%
set fileYear=%myFileDate:~6,4%
set currentDate=%date%
set currentMonth=%currentDate:~4,2%
set currentDay=%currentDate:~7,2%
set currentYear=%currentDate:~10,4%
The plan was to then convert the strings to integers, and then use a switch-case block to determine if the variance between dates was acceptable... blah blah blah.
Long story short - if you are limited to batch (and not creating secondary files -- such as a csv or the temp file suggested by MadsTheMan) you're going to have a really long script on your hands that still might have flaws (like leap year, etc unless you're adding even MORE code), when you could just make the comparison calculation using one line of code in other programs.

How can I save an interaction with a command line program to a file?

I need to create output files that include the input I'm providing. For example, a run of the program might look like:
Input command: do_things
Things have been done.
Input command: stop_doing_things
Things are no longer being done.
Where "do_things" and "stop_doing_things" are input from the user.
How can I output all of the above to a file using command prompt functions?
It's not clear what environment using "script " command linux will open a new shell and save everything done it to
This works for you, if you run it at last...
CMD > D:\mycmdout.txt
In that case, maybe you can capture your input as a variable. Echo the variable into the >> mycmdout.txt, then procede with the actual commands, again piped into >> mycmdout.txt as Sunny suggested.
SET /P variable=EnterInputHere
echo %variable% >> mycmdout.txt
EDIT: Be sure to use double >> as to append result to file.

Best automation scripting for command line commands in Windows?

I need to make a script that automates the following:
Read comma or tab separated values from the input file
Construct a command from them and run it
Get the command output, looks for substrings in it and update the log file based on the existence of a substring
I do this in Windows Server 2008, so I can do this in CMD or PowerShell but I am not sure they provide such possibilities. I can try Perl or C#, but I want to try a minimalistic approach first.
Minimalistic as far as coding - Perl
Minimalistic as far as installing new software - PowerShell (IIRS W.S.2008 included that?)
So many answers, and none providing a solution that would meet the requirements...
You didn't say what are the conditions to be checked against each CSV row, and what the CSV would be like, and what the log would be like - so I made it all up... Here's an example in BATCH:
#echo off
set csvfile=input.csv
set logfile=output.log
for /F "tokens=1,2,3 delims=," %%a in (%csvfile%) do call :processline "%%a" "%%b" "%%c"
exit /B 0
:processline
set param=%~3
set check=%param:um=%
rem if they are not equal - substring 'um' exists in it.
if not "$%check%" == "$%param%" (
rem this passes all params to output.
rem I'm not calling echo directly here, because there might be symbols, that will confuse CMD at the end of the %*.
call :output %*>> %logfile%
)
exit /B 0
:output
set colA=%~1
set colB=%~2
set colC=%~3
rem output to log
echo [%DATE% %TIME%] (%colB%) %colA% %colC%.
exit /B 0
Here's the example input file that I tested it with:
foo,1,dum
bar,3,dim
baz,15,dirum
And here's the resulting log messages:
[2009-10-14 14:57:35.87] (1) foo dum.
[2009-10-14 14:57:35.89] (15) baz dirum.
I hope this shows clearly, that BATCH is not nasty nor it is hard to use. :P
If you have further question about BATCH - don't be shy, post them all on SO. ;)
I would recommend going with Python (or Perl if you swing that way). These are very minimal tools to have to install on a machine and add all the functionality you need.
The string handling you describe is unpleasant in any shell (Bash included) unless you are using sed or awk... and that just gets esoteric. In the end you'll retain more hair if you go straight to a scripting language first.
Perl was called into existence to quickly solve these kind
of tasks. It should not take more 20 lines for this
particular problem.
It is also really easy to install:
Download ActivePerl (17.7 MB, Perl 5.10.)
Run the installer.

Simple DOS command-line to ignore data on a line after the last backslash

I'm creating a batch file to make multiple directories from a list in a text file
however after the directory is listed sometimes a filename is as well. Is there an easy way to have it ignore all data after the last \ on a line?
I might suggest that DOS batch isn't the right tool for this job, because it doesn't have built-in facilities for string manipulation like this would need.
If you have Perl available, you can do something like this:
#!/usr/bin/perl -w
while (<>) {
s/\\[^\\]*$//; # this removes a the last backslash and anything after it
mkdir $_;
}
You can use something like this:
#echo off
set filename="c:\temp\my files\file.txt"
for /f "tokens=*" %i in ("%filename%") do set filename="%~dpi"
echo %filename%
The result will be "c:\temp\my files\".