How to add empty space using batch script? - string

Is there any way to loop a text file which will add a EMPTY SPACE in front of each line?
commit.txt
commit c9bee
Merge: 7db
Author: TOM
Date: Fri Mar 13
Author: TIM
output.txt
commit c9bee
Merge: 7db
Author: TOM
Date: Fri Mar 13
Author: TIM

Here's one solution:
for /f "delims=" %i in (file) do #echo %i
Note that you must double the percents if you use this in a script (as opposed to interactive usage).

try this. This "overwrites" the original file.If you want to keep the name as output.txt just comment out the call to Overwriteoriginal
#echo off
REM makes sure the user passed in a file name
if [%1]==[] (
echo Must pass in a file name
) else (
Call:AddSpaceToEveryLine %1
Call:OverwriteOriginal %1
echo processed %1
)
GoTo:EOF
:OverwriteOriginal
REM overwrites original file with spaced file
del %1
rename output.txt %1
GoTo:EOF
:AddSpaceToEveryLine
REM there is actually one space after the equals sign
set space=
for /f "tokens=*" %%a in (%1) do (
echo %space%%%a >> output.txt
)
GoTo:EOF

-Editing here to mention escaping the space is not required, you can use ECHO 1 to get a (space)1.
Try escaping the space using ^
For example:
C:\Scripts>echo ^ string
string
C:\Scripts>echo string
string
-edit, this is what happens when you rush and don't read the question fully!
Try this:
C:\Scripts>for /f %a in (input.txt) do echo ^ %a
C:\Scripts>echo test1
test1
C:\Scripts>echo test2
test2

It can be done very easily and you don't need a for loop for it. Just declare a variable and and at the end of of your code just to do echo with the declared variable few times to your output file. In this case, I am sending to a file called c:\sample.txt. Here is an example:
#echo off
set blank=
:: Your main code goes here
echo. %blank% >> c:\sample.txt
echo. %blank% >> c:\sample.txt
echo. %blank% >> c:\sample.txt
echo. Author: TIM >> c:\sample.txt

Related

How to store the line numbers of the lines containing a specific string in a text file in an environment variable?

I currently have this batch code that tells me the amount of times this string comes up in a text file.
#ECHO OFF
set /a Numb=0
for /f %%i in ('FINDSTR /N .* %1') do (set /a Numb+=1)
echo %Numb%
I need another piece of code that outputs the line numbers that the text is on to a variable.
How to store the line numbers of the lines containing a specific string in a text file in an environment variable?
My batch code for this task which requires the specification of file name and search string as arguments on running the batch file with some error checking:
#echo off
setlocal EnableDelayedExpansion
set "FileName=%~1"
set "Search=%~2"
rem Exit batch file if the two required arguments were not specified.
if "%FileName%" == "" (
echo Error: There is no file name specified as first parameter.
goto ErrorOuput
)
if "%Search%" == "" (
echo Error: There is no search string specified as second parameter.
goto ErrorOuput
)
if not exist "%FileName%" (
echo Error: The file "!FileName!" does not exist.
goto ErrorOuput
)
set "LineNumbers="
for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /I /L /N /C:"%Search%" "%FileName%" 2^>nul') do set "LineNumbers=!LineNumbers!,%%I"
if "%LineNumbers%" == "" (
echo Info: The string "!Search!" could not be found in "!FileName!"
goto EndBatch
)
rem Remove the comma from begin of list of line numbers.
set "LineNumbers=!LineNumbers:~1!"
echo Found "!Search!" in "!FileName!" on the lines:
echo.
echo %LineNumbers%
goto EndBatch
:ErrorOuput
echo.
echo Usage: %~nx0 "file name" "search string"
:EndBatch
echo.
endlocal
pause
The error checking is not complete. There can still errors occur. For example the first argument could be *.txt which would produce a wrong result as FINDSTR outputs in this case first the file name, then a colon, next the line number, and one more colon instead of just line number and colon like when searching on a single file.
Run at least once in a command prompt window for example
findstr /I /L /N /C:"endbatch" "SearchString.bat"
with above batch code stored in file SearchString.bat in current directory to see what command FOR processes here.
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.
call /? ... explains %~1 and %~2
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
Read also the Microsoft article about Using command redirection operators for an explanation of 2>nul to redirect the error message output by FINDSTR to handle STDERR to device NUL to suppress it if the searched string could not be found in search file. The redirection operator > must be escaped here with ^ to apply the redirection on execution of FINDSTR instead of interpreting 2>nul as redirection for command FOR at an invalid position in command line.
How do I store the line numbers of matching lines for a string in a text file?
Use the following batch file.
test.cmd:
#echo off
setlocal enabledelayedexpansion
set line_numbers=
for /f "skip=2 delims=[]" %%i in ('find /n /i "%1" names.txt') do (
set line_numbers=!line_numbers! %%i
)
rem skip leading space
echo %line_numbers:~1%
endlocal
Notes:
Pass search string as an argument to test.cmd.
The file being searched is names.txt (you could pass this as a parameter as well).
The match line numbers are add to the variable line_numbers.
Example usage:
F:\test>type names.txt
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
F:\test>test bloggs
1 3 5
F:\test>test jones
2 4 6
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
find - Search for a text string in a file & display all the lines where it is found.
for /f - Loop command against the results of another command.
variables - Extract part of a variable (substring).

BATCH - Working with string(< , >) instead of redirection

The last word in every texts in testing.txt is "< /a>", I echo out the the word and it seems to be no problem, but when I echo out in the for loop, cmd gave me this error : "The system cannot find the file specified."
I know the problem is on the "<" and ">" sign, it stands for redirection, that's how the error created. How am I going to make cmd think I'm working with a string instead of redirection?
#echo off
setlocal EnableDelayedExpansion
set "remove_char=< /a>"
echo !remove_char!
for /f "skip=2 tokens=6*" %%a in (testing.txt) do (
set "string=%%a %%b"
set string=!string:%remove_char%=!
echo !string!
)
pause >nul
If you want to use < and > symbols as variables you have to change them to ^< or ^>
Otherwise they will be treated as Input or Output!
Maybe you can replace this line
set string=!string:%remove_char%=!
with
for %%i in (!remove_char!) do (set string=!string:%%i=!)

Match a variable to part of another variable in batch

I want to match a variable to part of the contents of another variable in batch. Here is some pseudo code for what I want to do.
set h= Hello-World
set f= This is a Hello-World test
if %h% matches any string of text in %f% goto done
:done
echo it matched
Does anybody know how I could accomplish this?
Based off of this answer here, you can use the FINDSTR command to compare the strings using the /C switch (modified from the linked answer so you don't have to have a separate batch file for comparing the strings):
#ECHO OFF
set h=Hello-World
set f=This is a Hello-World test
ECHO Looking for %h% ...
ECHO ... in %f%
ECHO.
echo.%f% | findstr /C:"%h%" 1>nul
if errorlevel 1 (
ECHO String "%h%" NOT found in string "%f%"!
) ELSE (
ECHO String "%h%" found in string "%f%"!
)
ECHO.
PAUSE
If the following conditions are met:
The search is case insensitive
The search string does not contain =
The search string does not contain !
then you can use:
#echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
if "!f:*%h%=!" neq "!f!" (
echo it matched
) else (
echo it did not match
)
The * preceding the search term is only needed to allow the search term to start with *.
There may be a few other scenarios involving quotes and special characters where the above can fail. I believe the following should take care of such problems, but the original constraints still apply:
#echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
for /f delims^=^ eol^= %%S in ("!h!") do if "!f:*%%S=!" neq "!f!" (
echo it matched
) else (
echo it did not match
)
Here's another way:
#echo off
set "h=Hello-World"
set "f=This is a Hello-World test"
call set "a=%%f:%h%=%%"
if not "%a%"=="%f%" goto :done
pause
exit /b
:done
echo it matched
pause

Batch: How to append the name of a variable instead of the value of that variable

I am trying to append strings to a text file. So far, my code looks like this:
echo -%appointment% >>C:\Users\Evan\Desktop\Programming\Events.txt
echo set /a h=(%hours%*3600)+(%minutes%*60) >>C:\Users\Evan\Desktop\Programming\Events.txt
echo set /a i=%day%-%dbf% >>C:\Users\Evan\Desktop\Programming\Events.txt
echo if %g% leq %h% if %b% equ %day% echo %appointment% %time% Today >>C:\Users\Evan\Desktop\Programming\Events.txt
echo if %b% lss %day% if %b% geq %i% echo %appointment% %time% %date% >>C:\Users\Evan\Desktop\Programming\Events.txt
The problem is, the variables %b% and %g% are dependent on the specific occurance. %b% and %g% change with date, so while their values will be accurate when I append them into the text file, their values will NOT be accurate when I actually want to convert the text file into a batch file and use it. How do I literally append the variable %b% as text and not its current value so that it can change every time I run the text file as a batch? If I try to append "%b%" in code with those quotations, in the occuring file, it is simply output as "".
Thank you.
Double the % for the % you wish to output literally.
% escapes % (ie causes it to be interpreted as an ordinary, not a special character.)
^ escapes most awkward characters like | - but not %

How to efficiently remove the first few chars of a row in text file?

Example of 2 rows in text file (abc.txt):
PMIP_TSD_2012120323.csv:03/12/2012,22:51:53,CAU TACS,TS,PPT4I_TS22, AJAY,595959,P,Legal Exit,(6 0) AJAY,G1234567M,SERVICES P L,8401352W,
PMIP_TSD_2012111300.csv:12/11/2012,23:20:13,CAU TACS,TS,PPT4O_TS32,ARUMUGAM,620466,P,Legal Exit,(5 0) ARUMUGAM,G686W,SUPERSONIC SERVICES P L,1982W,
I would like every row to start with the date instead of the csv file name. Meaning removing the PMIP......csv: for every row. How can i do this using batch file? I have hundreds of rows, i do not wish to do it manually. My file name is abc.txt and it is located in D:\Int\ KGX
This Batch file do that:
#echo off
cd /D "D:\Int\KGX"
(for /F "tokens=1* delims=:" %%a in (abc.txt) do (
echo %%b
)) > abc-NEW.txt
perl -npi -e 's/[^:]+://' /tmp/abc.txt yields:
03/12/2012,22:51:53,CAU TACS,TS,PPT4I_TS22, AJAY,595959,P,Legal Exit,(6 0) AJAY,G1234567M,SERVICES P L,8401352W,
12/11/2012,23:20:13,CAU TACS,TS,PPT4O_TS32,ARUMUGAM,620466,P,Legal Exit,(5 0) ARUMUGAM,G686W,SUPERSONIC SERVICES P L,1982W,
from your data. Hope that helps...
I can give you my thoughts about the problem
We can use C++ or Java to solve this problem
Open the file
In a loop we get the row in a String variable
use SubString (or some kind of similar functions or utilities) to specify the first index number (in our case 23)
Store the sub string in a new file
finish the loop
The new file is what you want, and hope that helps
This should do it
setlocal enabledelayedexpansion
for /f "tokens=1,* delims=:" %%a in (abc.txt) do (
echo !date!:%%b >>new.txt
)
del abc.txt /f /q
ren new.txt abc.txt

Resources