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
Related
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'm trying to loop a specific file and see if any line contains a certain word or text and I want to replace the whole line. I am not sure how I am suppose to do it.
Right now this what I have:
#echo off
setlocal enabledelayedexpansion
FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
Set Line="transaction.sic.lettreEnvironnementBackend"
IF %%G == %Line% (
replace that line with new text
)
)
pause
endlocal
#echo off
setlocal enabledelayedexpansion
Set "Line=transaction.sic.lettreEnvironnementBackend"
(
FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
IF "%%G"=="%Line%" (
echo replacement line
) else (echo %%G)
)
)>replacement_filename
pause
endlocal
Note that the replacement filename should not be the source filename. Once tested, move the replacement file to the original filename if required.
Note also that the instruction will exactly match the contents of line - there's no allowance for any other characters on the line.
The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.
Also easy in PowerShell.
Get-Content .\OutputFile.txt |
% { if ($_ -eq 'Warning message') { 'NEW WARNING' } else { $_ } }
I have a lot of text files that I need to append the name of the file at the end. I have just DOS commands available. I managed to append the name at the beginning using:
findstr "^" *.txt >new.dat.
Unfortunately I cannot append to the end using findstr "$" *.txt new1.dat.
I cannot understand why the $ (which should be [line position : end of line') is not working.
The second thing I'm trying to replace : (colon character) inside the file with the | (pipe). I use the script:
#echo off setLocal EnableDelayedExpansion
for /f "tokens=* delims= : %%a in (new1.dat) do ( echo "%%a| >>new2.dat ).
The file looks like this:
batch-2016-03-14-08-50-05.txt:6530635|GB|150316|6530635.png
batch-2016-03-14-08-50-08.txt:6530636|GB|150316|6530636.png
I just want to replace the : with the pipe (|)
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!
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%