Write to a file if it contains a word

March 9, 2011 at 12:25:24
Specs: Windows XP, AMD Athlon 5400+ // 3GB RAM
Hi all! I'm new here and I need a little help with my batch script.

Here's an example of what I want to do:
If a text file contains "myword", the script rewrites the file into a new one adding a line "mytexthere" under the line where it found "myword".

The original file:
fdafda
fd
saf
sdgdsgfdsgdfmywordgfsd
dsa
f
dsa

The new file:
fdafda
fd
saf
sdgdsgfdsgdfmywordgfsd
mytexthere
dsa
f
dsa

I found this so far:
@echo off > codes2.cfg & setLocal enableDELAYedexpansion

for /f "tokens=* delims= " %%a in (codes.cfg) do (
echo %%a >> codes2.cfg
if %%a equ myword (
echo mytexthere >> codes2.cfg
@pause
)
)

But it works only when myword is a whole line.


See More: Write to a file if it contains a word

Report •

#1
March 10, 2011 at 02:30:07
:: ==========================================
::
:: agibade.bat Thu 10-03-2011 17:17:16.63
@echo off > newfile & setLocal enableDELAYedeXpansion

for /f "tokens=1 delims=[]" %%a in ('find /n "myword" ^< myfile') do (
set M=%%a
)
set N=
for /f "tokens=* delims= " %%a in (myfile) do (
set /a N+=1
echo.%%a
if !N! equ !M! echo.mytexthere
) >> newfile


=====================================
Life is too important to be taken seriously.

M2


Report •

#2
March 10, 2011 at 05:02:58
Thanks for your reply. It worked.

But now I have another problem.
Is it possible to start writing after skipping a line or to delete the next line and then start writing?

Example:

Original:
dsadsa
fdsgsmyword
fadg
gasdgas

New file:
dsadsa
fdsgsmyword
fadg
mytexthere
gasdgas

Or:
dsadsa
fdsgsmyword
mytexthere
gasdgas


Report •
Related Solutions


Ask Question