Question

Add a line of text to a specific line in a file

Asked by: fiqzo

Hi,

I have a file called file.txt with the following:
test1
test2

I need to add a line "test1-1" between test1 and test2, using a batch file. It should look like:
test1
test1-1
test2

Please help.

Thanx.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-11-04 at 14:45:54ID20788011
Tags

add

,

file

,

line

,

text

Topic

MS DOS

Participating Experts
3
Points
125
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

    Free Tech Articles

    1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
      It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
    2. SCCM OSD Basic troubleshooting
      SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
    3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
      This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
    4. Create a Win7 Gadget
      This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
    5. Outlook continually prompting for username and password
      There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
    6. Backup Exchange 2010 Information Store using Windows Backup
      There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

    Cloud Class Webinars

    1. Avoiding Bugs in Microsoft Access
      Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
    2. Top 10 Best New Features in Visio 2010
      Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
    3. IT Consultant Business Secrets Revealed
      Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
    4. Disaster Recovery and Business Continuity
      Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
    5. Organize Your Visio Diagrams with Containers and Lists
      Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
    6. How to Us Objects, Properties, Events and Methods in Microsoft Access
      Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

    Join the Community

    Give a Little. Get a Lot.

    Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

    Join the Community

    Answers

     

    by: SethHoytPosted on 2003-11-04 at 15:33:25ID: 9683097

    This should do what you want:


    @echo off
    type nul>file.tmp
    for /f "delims=" %%i in (file.txt) do (echo %%i>>file.tmp) & if %%i==test1 echo test1-1

    >>file.tmp
    del file.txt
    ren file.tmp file.txt


    -Seth

     

    by: SethHoytPosted on 2003-11-04 at 15:35:36ID: 9683109

    Sorry, the for statement got broken up...


    @echo off
    type nul>file.tmp
    for /f "delims=" %%i in (file.txt) do (echo %%i>>file.tmp) & if %%i==test1 echo test1-1>>file.tmp
    del file.txt
    ren file.tmp file.txt

     

    by: K_2KPosted on 2003-11-04 at 15:49:24ID: 9683190

    This should let you add as many lines as you want after a given line.  Note that any method you use to set the target line you are searching for in file MUST be settled before you start the "FOR" loop.  Also, this is XP/2000 version,  9X/ME do not know the "/f" option in the "FOR" command.

    Enjoy,
    2K
    (\o/)


    ::setup target
    set TargetLine="test1"
    :: optional - remove :: in next line to get target from command line if given
    :: if NOT "%~1"=="" set TargetLine="%~1"


    :: write new file looking for target
    for /f "delims=" %%K in ( file.txt ) do (
      >>filenew.txt echo.%%K
      if "%%K"==%TargetLine% CALL :addlines
    )

    :: cleanup to replace file
    if exist file.txt if exist file.backup del file.backup
    if exist file.txt if exist filenew.txt ren file.txt file.backup
    if exist filenew.txt ren filenew.txt file.txt

    :: done - skip to end to avoide running addlines after done.
    goto :EOF

    :addlines
    :: you can add as many lines as you like here, and test2 follows after them
    >>filenew.txt echo test1-1
    goto :EOF

     

    by: K_2KPosted on 2003-11-04 at 16:00:24ID: 9683254

    echo %%i>>file.tmp  on the line that ends with the number 2 will echo the line to the screen with errors ( nothing) going to file.tmp

    Also, the & is parsed as belonging to the FOR loop so it may not do what it needs until after the loop finished with the file,  I haven't checked.  If it does that, try ^& and change
         echo %%i>>file.tmp  
    to
         >>file.tmp  echo %%i
    and that shorter program might be quite nifty.

    Good Luck,
    2K
    (\o/)

     

    by: SethHoytPosted on 2003-11-04 at 16:28:04ID: 9683409

    The & does not terminate a statement, so the parser treats it as part of the statement within the do context. I have tested it and it does work (at least for XP/2000).

     

    by: SteveGTRPosted on 2003-11-05 at 07:01:13ID: 9687167

    Here's batch file that uses a technique from Billious to process and keep the blank lines in a file:

    @echo off

    set _t1=Y

    if exist _temp2.dat del _temp2.dat > NUL
    find /N /V "" file.txt > _temp1.dat

    for /f "delims=" %%f in (_temp1.dat) do call :PROCESS %%f

    del _temp1.dat>NUL
    echo _temp2.dat has results of conversion

    set _t=
    goto EXIT

    :PROCESS

    set _t=%~1

    if "%_t1%"=="" goto LOOP

    set _t1=
    goto EXIT

    :LOOP

    if "%_t:~0,1%"=="]" goto TESTIT

    set _t=%_t:~1%
    goto LOOP

    :TESTIT

    set _t=%_t:~1%

    if "%_t%"=="" goto EMPTYLINE

    echo %_t%>>_temp2.dat

    if %_t%==test1 echo test1-1>>_temp2.dat
    goto EXIT

    :EMPTYLINE
    echo.>>_temp2.dat
    goto EXIT

    :EXIT

    Good Luck,
    Steve

     

    by: K_2KPosted on 2003-11-05 at 08:04:22ID: 9687732

    <<<
         echo %_t%>>_temp2.dat
    >>>
    This could fail.

    With all due respect to Billious, Steve, Seth, Microsoft examples - (I take that back - MS does this too, but with all the resources at their disposal they have no excuse) - and everyone else who codes this way - it's less than 100% accurate,  and the example files given in this question fall squarely in the set of data that could cause this line to fail.



    At some point in future changes to the data, the user might add lines:
         new test line 1
         new test line 2
    Then at some time in the :PROCESS %_t% will be "new test line 1"
    So the parser will build the expanded line as
         echo new test line 1>>_temp2.dat
    Now it's time to set up the redirect - according to this line, stdout (channel 1) is to go to a file.  The data to send is:
         new test line
    That line of output is changed, but not because the program wanted it.  It simply does not realize the parser setup redirection on that line as it was directed, instead of assuming which channel to redirect as it needed to on other lines.
    Also at some time in the :PROCESS %_t% will be "new test line 2"
    So the parser will build the expanded line as
         echo new test line 2>>_temp2.dat
    Now it's time to set up the redirect - according to this line, stderr (channel 2) is to go to a file.  If this is running in a visible window, the user will see
         new test line
    and the errors of that echo (there are no errors here) will go to the file.  That line of output is effectively deleted, although all of the logic above does NOT indicate it should be.  Well, the program does not think it was deleted, but it simply does not realize the parser redirected that line differently than the rest.

    This line has no such side-effects, since any possible number at the end of lines cannot be accidentally mistaken for part of the redirect directive.
         >>_temp2.dat echo %_t%


    Hope this helps,
    2K
    (\o/)

     

    by: SethHoytPosted on 2003-11-05 at 08:38:18ID: 9687996

    But doesn't the parser convert the >> to 1>> anyways so that can't happen?

     

    by: K_2KPosted on 2003-11-05 at 09:23:31ID: 9688389

    Oh, my aching head,  I'm so confused.

    This was a real problem I prooved on an Old box years ago (95 or DOS 6).  Since then I've prooved on NT/2000/XP that trailing spaces followed by redirects still cause problems as before.  That's only if trailing spaces matter to the data, and because old timers used to add space to prevent this parser problem.  
    I just now checked and see you are correct, on both NT and 2K the parser has corrected this by changing ">>filename.ext" to " 1>>filename.ext" and the interpreter correctly restrips that last added space from the output.  9X/ME?  I don't know but is moot to this question since they don't do "FOR /f" anyway.  Lines typed with a single digit hard coded and separated by white space are the only ones that still affect redirection.

    So Steve's code is solid and also preserves empty lines which none of our other stuff did.

    Two retractions in one day,  I think I'll quit while I'm behind.

    Thanks Seth for keeping me straight and teaching me something.

    2K
    (\o/)

     

    by: fiqzoPosted on 2003-11-06 at 06:15:19ID: 9694061

    Thanx guys!

    K_2K your script worked superbly. I modified it a bit with this

    :: if string exists stop processing
    for /f "delims=" %%K in ( file.txt ) do (if "%%K"=="test1-1" goto eof)

    so should the batch file run via a login script the string will not be inserted again.

    Thanx again.

     

    by: K_2KPosted on 2003-11-06 at 07:25:28ID: 9694638

    Nice addition.  The data file is too short to notice the difference in speed, but this might be a bit faster:

    :: if string exists stop processing
    >nul findstr /b /e "test1-1"  file.txt && echo eof


    We could also add a flag and check in :addlines to delay the new addition until the line after the target is seen not to be "test1-1" avoid reading the file twice.  Caching makes that almost pointless, and that also would create a possible un-needed temp file on every logon, actually taking longer than two file reads.

    Enjoy,
    2K
    (\o/)

     

    by: SteveGTRPosted on 2003-12-08 at 07:16:12ID: 9896876

    Submitter seems to be satified with K_2K's script. Maybe a split between K_2K and SethHoyt.

    20120131-EE-VQP-002

    3 Ways to Join

    30-Day Free Trial

    The Experts

    98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

    He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

    The Experts

    97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

    The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

    Testimonials

    "...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

    Testimonials

    "I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

    Testimonials

    "WOW! You guys have great, active, and knowledgeable people on here." moore50

    Business Clients

    Business Clients

    In the Press

    "If you’ve got a question... Experts Exchange can supply an answer.”

    In the Press

    "...an invaluable aid for both IT professionals and those who require tech support."

    In the Press

    "where IT professionals provide quick answers on just about any topic"

    Business Account Plans

    Loading Advertisement...