here's a text file txtfile.txt
line1
line2
add after this line
line4
etc
etc
i want to create a batch file which can add a line after add after this line with the user entered info. keeping the add after this line intact.
example:
enter info: asdf
and the file becomes
line1
line2
add after this line
asdf
line4
etc
etc
i think that the basic process would be to loop through the file copying it and when i find the line, adding the line and then looping through the rest. i want to know how to do it.
#ECHO OFF
SETLOCAL
SET /p info="enter info : "
:: read addafter line
(
FOR /f "delims=" %%i IN (poison1.txt) DO (
SET addafter=%%i
FOR /f "delims=" %%n IN (' findstr /n "^" txtfile.txt') DO (
SET line=%%n
SETLOCAL ENABLEDELAYEDEXPANSION
SET line=!line:*:=!
ECHO(!line!
IF "!line!"=="!addafter!" ECHO(%info%
ENDLOCAL
)
)
)>newfile.txt
FC newfile.txt txtfile.txt
GOTO :eof
Where poison1.txt contains the one line
"A line !of! ] many < & >var*ied %poison ^ char;ac(ters) | like "," a\nd+so=on"
and txtfile.txt contains this line.
Read the line from the poison1.txt file to addafter
For each line in the add-to-me file
Number the line to catch empty lines
Remove the number and first colon (added by FINDSTR)
Output the line verbatim
if the line matches the target, output the extra line
done!
Related
I want to insert a string of text say "hello" in a particular line say n (12 or 23 or some other number) using batch script. I know batch script is bad but unfortunately the requirement for this is batch script.
Here's what I've tried
#echo off
setlocal enableextensions disabledelayedexpansion
set "nthline=TEXT"
(for /f "usebackq tokens=* delims=" %%a in (c.txt) do (
echo(%%a
if defined nthline (
echo(%nthline%
set "nthline="
)
))
This code I got from here but it only inserts to the second line I cannot make it go beyond that.
Here is what the text file contains
aaaa
bbbb
cccc
dddd
ffff
gggg
hhhh
It inserts the string after aaaa. How can I make it insert at bbbb or ffff I'm new to batch scripting so Any help is greatly appreciated
The code you have posted is designed to insert an extra line after the first one.
To insert at a certain point you need to somehow predefine the target line number and a line number, then compare these numbers for equality and return the extra line of text ‐ line in the following script:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constante here:
set "_FILE=c.txt" & rem // (text file to insert a line of text into)
set "_TEXT=hello" & rem // (text of the inserted line)
set /A "_NUM=4" & rem // (number of the line where the new line is inserted)
set "_REPLAC=#" & rem // (set to anything to replace the target line, or to nothing to keep it)
set "_TMPF=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (path and name of temporary file)
rem // Write result into temporary file:
> "%_TMPF%" (
rem // Loop through all lines of the text file, each with a preceding line number:
for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
rem // Store current line including preceding line number to a variable:
set "LINE=%%L"
rem // Set the current line number to another variable:
set /A "LNUM=%%L"
rem // Toggle delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem // Compare current line number with predefined one:
if !LMUN! equ %_NUM% (
rem // Line numbers match, so return extra line of text:
echo(!_TEXT!
rem // Return original line (without preceding line number) only if it is not to be replaced:
if not defined _REPLAC echo(!LINE:*:=!
) else (
rem // Line numbers do not match, so return original line (without preceding line number) anyway:
echo(!LINE:*:=!
)
endlocal
)
)
rem // Move temporary file onto original one:
move /Y "%_TMPF%" "%_FILE%"
endlocal
exit /B
I want to delete the lines that containing a certain string except the first line(that contains the particular string that I want delete).
findstr /v MyString file.txt > newfile.txt
I used this code to delete but as you see this delete all string(also the first line).
How can I do?
For example, this is the first file (file.txt):
Anna;Mary;sylvia
1;345;100
23;34;45
Anna;Mary;sylvia
23;54;99
Anna;Mary;sylvia
10;23;34
Now I expect this (newfile.txt):
Anna;Mary;sylvia
1;345;100
23;34;45
23;54;99
10;23;34
SOLUTION
I found a solution to my problem.
Here this the piece of code:
set /p var=<file.txt
echo %var% >> newfile.txt
findstr /v MyString file.txt > newfile2.txt
type newfile2.txt >> newfile.txt
del newfile2.txt
In the first two lines I take the header and write it on the newfile. In the third line I clear all rows with MyString and write the other lines on newfile2.txt and finally append the newfile2(with all lines) with newfile(where there is the header).
#Echo off
Set File=file.txt
Set NewFile=NewFile.txt
Set /P Header=<%File%
(Echo:%Header%
Findstr /xlv /C:"%Header%" %File%
) > %NewFile%
A longer variant with some explanations, here getting the file to process via cmd line
:: Q:\Test\2017\08\23\OneHeader.cmd
#Echo off
:: Strip duplicates of the header (first line) from the File passed as argument.
:: creates a backup File with _bak appended to the name without extension
If "%~1" equ "" (Echo No File name passed as argument & Pause & exit /B 1)
If not exist "%~1" (Echo File name %1 not found & Pause & exit /B 1)
Set "File=%~1"
Set "FileBackup=%~dpn1_bak%~x1"
:: Read first line of File into variable Header
Set /P Header=<"%File%"
Move /Y "%File%" "%FileBackup%" 2>NUL
:: write Header and old content stripped from all headers to output
(Echo:%Header%
Findstr /xlv /C:"%Header%" %FileBackup%
) > "%File%"
I have a problem taking a text file with 2 lines of text inside of it, and converting each line of the file into a separate variable.
I thought I could just repeat the same process for getting one line of text and just add skip=1 next to delims= and change the name of the variable it goes into, this did not work how I planned and I can't figure out another way to do it.
Here is my code:
#echo off
for /f "delims=" %%a in (file.txt) do (
set line1=%%a
)
for /f "skip=1 delims=" %%a in (file.txt) do (
set line2=%%a
)
echo %line1%
echo %line2%
pause
The text inside the file file.txt is this:
This is the Text on line 1
This is the Text on line 2
Instead of what i thought the output was going to be -
This is the Text on line 1
This is the Text on line 2
Press any key to continue...
It was this:
This is the Text on line 2
This is the Text on line 2
Press any key to continue...
It just prints the second line of the text file for both of the echos!
Please respond to this question as me not knowing how to do this is really bugging me
Thanks, Alex
This is a simple way:
#echo off
< file.txt ( set /P "line1=" & set /P "line2=" )
echo %line1%
echo %line2%
If you want to read more lines, or a variable number of lines, I suggest you to read Arrays, linked lists and other data structures in cmd.exe (batch) script
Take a look at this:
vars.txt (file with variables):
var1
var2
var3
tast.bat:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET varFile=vars.txt
SET i=1
FOR /F %%l IN (%varFile%) DO (
SET line!i!=%%l
SET /a i=!i!+1
)
ECHO !line1!
ECHO !line3!
PAUSE
Output:
var1
var3
This will work regardless how many lines/variables you have. If you have only one, it will be stored in !line1!, if you have 1000, the 500th line will be stored in !line500! and so on.
This should work for lines with spaces by the help of tokens=*
#echo off
rem Creating env testing
(echo First blank line should be skiped
for /l %%i in (1,1,30) do ( echo This is the Text on line %%i)
)>_vars.tmp
setlocal enabledelayedexpansion
set i=1
for /F "skip=1 tokens=*" %%a in (_vars.tmp) do (
set line!i!=%%a
set /a i+=1
)
echo:!line1!
echo:!line3!
echo:!line30!
echo:!line100!
echo checking _vars.tmp
more _vars.tmp
del _vars.tmp
pause
exit /b 0
I am totally new on writing batch script,busy with the tutorials with the example below I can learn a thing or two.I really need help to write a batch script to insert a line of text at the middle of existing text file.
For example given the file myfile.txt with the contents:
a
bcd
efg
hjiklmnop
q
rs
t
uvwxyz
The the command ./put-in-middle.sh "=== === ===" myfile.txt
should modify the file to:
a
bcd
efg
hjiklmnop
=== === ===
q
rs
t
uvwxyz
#echo off
rem Count the number of lines in the file with FIND
for /F %%a in ('find /C /V "" ^< %2') do set numLines=%%a
rem Get the number of middle line
set /A middle=numLines/2
rem Process all lines, use FINDSTR /N to insert line numbers
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %2') do (
rem Echo the original line
echo/%%b
rem If the line is the middle one...
if %%a equ %middle% (
rem Insert the new line
echo %~1
)
)
Create previous Batch file as put-in-middle.bat and execute it this way:
put-in-middle "=== === ===" myfile.txt
Notes:
Previous program does not check for errors, like missing parameters. This checking may be added, if you wish.
The slash in the command echo/%%b is inserted to avoid the message "ECHO is on" if the line is empty. If the line may contain the string "/?", then the command should be changed to echo(%%b to avoid that the echo help be displayed in this case (the left parentheses is the only character that do that).
If the file contains Batch special characters, like < > | & ), the echo/%%b command fail. In this case, a special processing of files lines must be added. The same point apply to the new inserted line.
Previous program just display in the screen the new file. If you want to replace the original file, the output must be redirected to an auxiliary file and replace the original one at end:
.
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %2') do (
. . .
)) > auxiliar.txt
move /Y auxiliar.txt %2
Using sed and assuming even number of lines:
sed $(( $(wc input -l | cut -d' ' -f1) / 2))'a=== === ===' input
And this is the script version put-in-middle.sh:
line=$1
file=$2
sed $(( $(wc $file -l | cut -d' ' -f1) / 2))"a$line" $file
I have a text file which has more than 200 lines in it, and I just want to add a new line before line 4. I'm using Windows XP.
Example text file before input:
header 1
header 2
header 3
details 1
details 2
After output:
header 1
header 2
header 3
<----- This is new line ---->
details 1
details 2
I believe you are using the
echo Text >> Example.txt
function?
If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.
Example:
echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
#ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200 line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
You can use:
type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
or something like this:
echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
Suppose you want to insert a particular line of text (not an empty line):
#echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
#echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%