1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Batch program help

Discussion in 'Programming & Webmastering' started by thepollock89, Apr 3, 2012.

  1. thepollock89 New Member

    Joined:
    Apr 3, 2012
    Messages:
    5 (0.00/day)
    Thanks Received:
    1
    The purpose of my code is basically to store contacts, view them, and search by name.
    It all seems to work fine so far but I don't know how to go about making the batch search for a specific name at the start of each line of the batch file and delete the whole line.

    I was thinking maybe I can make the output of the chosen line move to a temporary text file that gets deleted after a number is added or the list of numbers are viewed. The section of the code named "filtered" is the part where i was hoping to add this function if possible.

    I already did Google searches but I was looking for a noob friendly answer.
    If any can help I would greatly appreciate it.

    Code:
    @echo off
    
    cd %userprofile%
    if exist contacts.txt goto start
    else if not exist contacts.txt goto create
    
    :start
    cls
    color 34
    color 04
    
    echo =================================================
    echo v view contacts
    echo a add contact
    echo f use filter
    echo e exit
    echo =================================================
    set /p var=view contacts, add one, or delete one?
    if "%var%"=="v" goto list
    if "%var%"=="a" goto add
    if "%var%"=="f" goto filtered
    if "%var%"=="e" exit
    
    :list
    cls
    cd %userprofile%
    type contacts.txt
    echo =================================================
    echo press any key to return to the main menu......
    pause>nul
    del unwanted.txt /q
    goto start
    
    :add
    cls
    echo =================================================
    cd %userprofile%
    set /p var2=enter a name:
    set /p var3=enter first 3 digits:
    set /p var4=enter second three digits:
    set /p var5=enter last 4 digits:
    echo =================================================
    echo %var2% - %var3%-%var4%-%var5% >> contacts.txt
    echo =================================================
    echo press any key to return to the main menu.....
    pause>nul
    del unwanted.txt /q
    goto start
    
    :create
    cd %userprofile%
    contacts>contacts.txt>nul
    goto start
    
    :filtered
    cls
    set /p var6=type the name of the contact you want to delete:
    
    
     
    Last edited: Apr 5, 2012
  2. FordGT90Concept

    FordGT90Concept "I go fast!1!11!1!"

    Joined:
    Oct 13, 2008
    Messages:
    14,636 (6.20/day)
    Thanks Received:
    4,342
    Location:
    IA, USA
    ...why not use VB?
     
    CrackerJack says thanks.
    Crunching for Team TPU
  3. Mindweaver

    Mindweaver Moderato®™ Staff Member

    Joined:
    Apr 16, 2009
    Messages:
    5,498 (2.53/day)
    Thanks Received:
    3,107
    Location:
    Statesville, NC
    Not to give you the total answer.. I would read the file to memory then rewrite the file with out said line of text. :toast: If you don't have VB like Ford suggested.. You could always write it in VBS, but a batch file will work fine. I have to say I still use batch files daily myself.. but the batch files are ones I've wrote in the past, and see no reason to convert to VB.

    EDIT: Also, if you don't have VB then go register for VB 2010 Express or you could do what you want with access.
     
    Last edited: Apr 4, 2012
    Crunching for Team TPU
  4. thepollock89 New Member

    Joined:
    Apr 3, 2012
    Messages:
    5 (0.00/day)
    Thanks Received:
    1
    I realize there's other ways of doing it but I specifically am looking to do it in a batch.
    I did change the code a little bit. All I have left to do is make it do is read a txt file and delete the line that starts with the name the user specifies. If i can manage that with the phone numbers I can do the same for the storing passwords.

    I might need some ideas on how exactly I can password protect the second half of my code(see section 2 in code) with out it being able to be overwritten on second time running or accessed at all when I convert it into an exe. heres my updated code:




    Code:
    
    @echo off
    title Phone Book
    cd %userprofile%\documents
    if exist contacts.txt goto start
    else if not exist contacts.txt goto create
    
    rem===================================================
    rem=======SECTION=1:CONTACTS==========================
    rem===================================================
    
    :start
    cls
    color 34
    color 04
    
    echo -------------------------------------------------
    echo v view contacts
    echo a add contact
    echo f use filtered search
    echo p manage passwords
    echo e exit
    echo -------------------------------------------------
    set /p var= view contacts or add one?
    if "%var%"=="v" goto list
    if "%var%"=="a" goto add
    if "%var%"=="f" goto filtered
    if "%var%"=="p" goto startpw
    if "%var%"=="e" exit
    
    :list
    cls
    type contacts.txt
    echo -------------------------------------------------
    echo press any key to return to the main menu......
    pause>nul
    goto start
    
    :add
    cls
    echo -------------------------------------------------
    set /p var2=enter a name:
    set /p var3=enter first 3 digits:
    set /p var4=enter second three digits:
    set /p var5=enter last 4 digits:
    echo -------------------------------------------------
    echo %var2% - %var3%-%var4%-%var5% >> contacts.txt
    echo -------------------------------------------------
    echo press any key to return to the main menu.....
    pause>nul
    goto start
    
    :create
    contacts>contacts.txt>nul
    attrib contacts.txt +h
    goto start
    
    :filtered
    cls
    set /p var6=type the name of the contact you want to delete:
    echo -------------------------------------------------
    FINDSTR "%var6%" contacts.txt
    echo ------------------------------------------------- 
    if errorlevel 1 goto start
    echo press any key to return to main menu.....
    pause>nul
    goto start
    
    rem================================================================
    rem==============SECTION=2:PASSWORDS===============================
    rem================================================================
    
    :startpw
    if exist passwords.txt goto startpw2
    else if not exist contacts.txt goto createpw
    
    :startpw2
    cls
    color 34
    color 04
    echo -------------------------------------------------
    echo v view passwords
    echo a add password
    echo f use filtered search
    echo p phone book
    echo e exit
    echo -------------------------------------------------
    set /p var10=view passwords or add one?
    if "%%"=="v" goto viewpw
    if "%%"=="a" goto addpw
    if "%%"=="f" goto filtervwpw
    if "%%"=="p" goto start
    if "%%"=="e" exit
    
    
    :createpw
    passwords>passwords.txt>nul
    attrib passwords.txt +h
    goto startpw2
    
    :createpw2
    
    :addpw
    
    :viewpw
    
    :filtervwpw
    
    
     
    Last edited: Apr 5, 2012
  5. Mindweaver

    Mindweaver Moderato®™ Staff Member

    Joined:
    Apr 16, 2009
    Messages:
    5,498 (2.53/day)
    Thanks Received:
    3,107
    Location:
    Statesville, NC
    Dude, put your code into [code] [/code] tags just to help others read it. But like I said don't try to delete the line of text.. just rewrite the text file with out the line of text.. Much easier.. There is way's to do it and some require you to install sed, awk, or perl... You can google and find which one you prefer or you could... and I don't like giving answers.. and you haven't asked the right questions, but this time here you go..
    Code:
    type contacts.txt | findstr /v Line_to_remove
    :toast:
     
    Last edited by a moderator: Feb 19, 2014
    Crunching for Team TPU
  6. thepollock89 New Member

    Joined:
    Apr 3, 2012
    Messages:
    5 (0.00/day)
    Thanks Received:
    1
    I didnt know about the whole code thing. sorry. i am aware now that i was asking the wrong questions. i just started using the delims and tokens with the for /f command and just about got it. i just don't use the pipe symbol as often as a should. i cant believe i didn't think of that. thank you kind sir.

    Code:
     
    
    :deletecont
    cls
    type nul > temp.txt
    type nul > temp2.txt
    set /p var99=enter the name of the contact you wish to delete:
    findstr /v /n %var% (contacts.txt) >> temp.txt
    
    for /f "tokens=2,3 delim=.*" %%v in (temp.txt) do echo %%v >> temp2.txt
    del temp.txt
    ren temp2.txt contacts2.txt
    pause
    goto start
    
    
     
  7. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (4.67/day)
    Thanks Received:
    5,622
    Location:
    Cheeseland (Wisconsin, USA)
    Welcome to TPU tp89 :toast:

    I'm not knocking your decision, but why would you want to write what is basically a database type program in a batch scripting language?

    Just curious. :)
     
  8. thepollock89 New Member

    Joined:
    Apr 3, 2012
    Messages:
    5 (0.00/day)
    Thanks Received:
    1
    now i am getting an error when i tried to pipe it. the same error i was having before.
    it tells me it cant open contacts.txt when i know I'm in the right directory.

    Code:
    :deletecont
    cls
    set /p var99=enter the name of the contact you wish to delete:
    type contacts | findstr /v %var% (contacts.txt) >> temp.txt
    pause
    goto startcont
    
    this way gave me 2 errors. the delims wont accept a period and it still refuses to read the text file.

    Code:
    
    :deletecont
    cls
    type nul >temp.txt
    type nul >temp2.txt
    set /p var99=enter the name of the contact you wish to delete:
    
    for /f "tokens=2 delim=." %%v in (contacts.txt) do echo %%v >> temp.txt
    findstr /v %var% (contacts.txt) >> temp2.txt
    del contacts.txt
    del temp.txt
    ren temp2.txt contacts.txt
    goto startcont
    
    
    uh. i just don't wanna skip anything in batch filing before i move on to visual basic or vbscript. i wanna get down as much as i can and i figured a shitty database program would be descent practice.
     
    Kreij says thanks.
  9. FordGT90Concept

    FordGT90Concept "I go fast!1!11!1!"

    Joined:
    Oct 13, 2008
    Messages:
    14,636 (6.20/day)
    Thanks Received:
    4,342
    Location:
    IA, USA
    Just saying, you'd save yourself a lot of trouble if you skipped batch and went straight for Visual Basic. You can throw a GUI on it and everything too so it's much easier to use. VB may look intimidating but it is actually substantially easier to use than what you're trying to do now.

    Batch is meant to call other programs to do the heavy lifting--not do the heavy lifting itself. In fact, all the goto statements batch requires are an example of how not to program.

    I don't mean to sound harsh nor offensive. I mean to steer you on a better path for the goals it appears you are trying to achieve.


    Example Batch:
    Code:
    cls
    color 34
    color 04
    
    echo -------------------------------------------------
    echo v view contacts
    echo a add contact
    echo f use filtered search
    echo p manage passwords
    echo e exit
    echo -------------------------------------------------
    set /p var= view contacts or add one?
    if "%var%"=="v" goto list
    if "%var%"=="a" goto add
    if "%var%"=="f" goto filtered
    if "%var%"=="p" goto startpw
    if "%var%"=="e" exit
    Example VB.NET:
    Code:
            Console.Clear()
            Console.ForegroundColor = ConsoleColor.Red
            Console.WriteLine("-------------------------------------------------")
            Console.WriteLine("v view contacts")
            Console.WriteLine("a add contact")
            Console.WriteLine("f use filtered search")
            Console.WriteLine("p manage passwords")
            Console.WriteLine("e exit")
            Console.WriteLine("-------------------------------------------------")
            Select Case Console.ReadKey().KeyChar.ToString().ToLower()
                Case "v"
                    ' List
                Case "a"
                    ' Add
                Case "f"
                    ' Filtered
                Case "p"
                    ' Password
                Case "e"
                    ' Exit
            End Select
     
    Last edited: Apr 5, 2012
    Mindweaver says thanks.
    Crunching for Team TPU
  10. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (4.67/day)
    Thanks Received:
    5,622
    Location:
    Cheeseland (Wisconsin, USA)
    Yeah, but if has the chutzpah to make a database program in batch, he's ready for anything in VB. :D
     
    Mindweaver and FordGT90Concept say thanks.
  11. Mindweaver

    Mindweaver Moderato®™ Staff Member

    Joined:
    Apr 16, 2009
    Messages:
    5,498 (2.53/day)
    Thanks Received:
    3,107
    Location:
    Statesville, NC
    thepollock89 FordGT90Concept is right. You could write it so much easier with vb and it would be much easier for the end user to add data to your database. If you are just doing this to achieve a goal of I did it, and not something someone would use daily... Then why not try using something to help you do what you want.. Like Ford suggested have the batch call a program like "sed".. Only thing is Sed is a Unix program, but it has been ported to Win32 here. :toast: aahhh I just thought of my old RS6000.. :d


    ^^ This! :toast:
     
    Last edited: Apr 5, 2012
    Crunching for Team TPU
  12. thepollock89 New Member

    Joined:
    Apr 3, 2012
    Messages:
    5 (0.00/day)
    Thanks Received:
    1
    thanks for all the info everyone. i will try visual basic next. there's just so many languages and information its hard to take in all at once considering i cant go to school so i have to self teach my self everything.

    the basics of c++ i was doing 2 years ago and making batch files for the past month or 2 is the full extent of my programming experience so i just don't wanna jump into anything too crazy yet.

    i got it working fine. i couldn't find an option for marking the thread solved so i was hoping an admin can do it for me.
     
    Last edited by a moderator: Apr 5, 2012
  13. FordGT90Concept

    FordGT90Concept "I go fast!1!11!1!"

    Joined:
    Oct 13, 2008
    Messages:
    14,636 (6.20/day)
    Thanks Received:
    4,342
    Location:
    IA, USA
    Most K-12 schools only teach VB.NET. Colleges/universities do VB.NET, then C#, then Java, then C++.

    VB is verbose and an introduction to Visual Studio and the .NET Framework.
    C# is C-style syntax (not verbose) using the same tools (Visual Studio and .NET Framework).
    Java also uses C-style syntax using open-source tools.
    C++ is C returning back to Visual Studio.
     
    Last edited: Apr 5, 2012
    Crunching for Team TPU
  14. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (4.67/day)
    Thanks Received:
    5,622
    Location:
    Cheeseland (Wisconsin, USA)
    It doesn't need to be marked "solved". Other people may wish to comment or ask questions about things in the thread so we don't close them unless the thread is problematic or an ended contest.
    Threads in the P&W section don't usually fill with crap when they hit EOL like they do in some of the other sections. They just fade into oblivion until someone zombies one. lol

    I've also been merging your double posts. Please use the edit button to add to posts instead of making consecutive posts.

    As for learning another language, ask any questions you may have.

    I prefer C# as it's a RAD language and you can do a lot quickly.
    C++ is the way to go if you want to write drivers (and other low level hw access) or games.
    VB is fine, but I'm not very fond of any versions of BASIC.
    C is not an OOP language. Can't really recommend that.
    JAVA is great if you need cross-platorm compatibility.
    PHP and Javascript if you want to code web sites/pages.
    Various other scripting languages if you want to mod games (depends on the scripting language the game uses)
    FORTRAN is still used for high level mathematics (like FFTs and such)
    PASCAL is like learning Latin. It's a dead language, but fun at parties.
    COBOL ... just say no.

    You will also find that the coders on TPU love to go off on tangents and argue about semantics, best practices and coding style.
    If we take one of your threads off topic, just post "HEY GUYS ... Remember me?" :roll:
     
    Last edited: Apr 5, 2012
  15. dick123 New Member

    Joined:
    Apr 19, 2012
    Messages:
    3 (0.00/day)
    Thanks Received:
    0
    Great post so thanks its a very helpful.
     
  16. Aquinus

    Aquinus Resident Wat-man

    Joined:
    Jan 28, 2012
    Messages:
    7,240 (6.25/day)
    Thanks Received:
    2,729
    Location:
    Concord, NH
    Ruby is a really cool scripting language. I've been playing around with it a lot. It's written a little strangely compared to BASIC and C-like languages, but it enables you to do a lot really easily.

    Here is an example of some Ruby. This script pings OpenVPN server clients listed in the ipp.txt file in /etc/openvpn/ to report which clients are connected and those who are not. It also has the ability to show any combination of connected and disconnected users as well as providing the data in XML.

    Code:
    #!/usr/bin/ruby1.9.1
    require "nokogiri"
    
    ipfile = File.open('/etc/openvpn/ipp.txt')
    threads = Array.new
    results = Array.new
    
    connected = false
    disconnected = false
    as_xml = false
    
    ARGV.each do |arg|
      case arg
      when "--xml"
        as_xml = true
      when "--connected"
        connected = true
      when "--disconnected"
        disconnected = true
      end
    end
    
    if !connected and !disconnected
      print "Usage: ovpn-stat.rb [--connected] [--disconnected] [--xml]\n"
      print "    --(dis)connected displays users who fit that connection status.\n"
      print "    --xml returns the result as xml.\n"
      exit
    end
    
    ipfile.each do |line|
      threads << Thread.new do
        splitted = line.split(',')
        result = `ping -q -c 1 #{splitted[1]}`
        if($?.exitstatus == 0)
          cstr = "Connected"
        else
          cstr = "Disconnected"
        end
        r = Hash.new
        r["user"] = splitted[0]
        r["ip"] = splitted[1].sub(/\n/, '')
        r["status"] = cstr
        if (cstr == "Connected" and connected) or (cstr == "Disconnected" and disconnected)
          results << r
        end
      end
    end
    
    threads.each do |i|
      i.join
    end
    
    if as_xml
      builder = Nokogiri::XML::Builder.new do |xml|
        xml.vpnclients {
          results.each do |ci|
          xml.client {
            xml.user ci["user"]
            xml.ip ci["ip"]
            xml.status ci["status"]
          }
          end
        }
      end
      print builder.to_xml
      exit
    end
    
    results.each do |i|
      print "#{i["user"]}@#{i["ip"]} - #{i["status"]}\n"
    end
     

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page