# Batch program help



## thepollock89 (Apr 3, 2012)

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.


```
@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:
```


----------



## FordGT90Concept (Apr 3, 2012)

...why not use VB?


----------



## Mindweaver (Apr 4, 2012)

Not to give you the total answer.. I would read the file to memory then rewrite the file with out said line of text.  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.


----------



## thepollock89 (Apr 4, 2012)

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:





```
@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
```


----------



## Mindweaver (Apr 5, 2012)

thepollock89 said:


> 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:
> ...



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.. 
	
	



```
type contacts.txt | findstr /v Line_to_remove
```


----------



## thepollock89 (Apr 5, 2012)

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. 


```
: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
```


----------



## Kreij (Apr 5, 2012)

Welcome to TPU tp89 



> I realize there's other ways of doing it but I specifically am looking to do it in a batch.



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.


----------



## thepollock89 (Apr 5, 2012)

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. 


```
: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.


```
: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
```



Kreij said:


> Welcome to TPU tp89
> 
> 
> 
> ...



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.


----------



## FordGT90Concept (Apr 5, 2012)

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:

```
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:

```
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
```


----------



## Kreij (Apr 5, 2012)

Yeah, but if has the chutzpah to make a database program in batch, he's ready for anything in VB.


----------



## Mindweaver (Apr 5, 2012)

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.  aahhh I just thought of my old *RS6000*.. :d




Kreij said:


> Yeah, but if has the chutzpah to make a database program in batch, he's ready for anything in VB.



^^ This!


----------



## thepollock89 (Apr 5, 2012)

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.


----------



## FordGT90Concept (Apr 5, 2012)

thepollock89 said:


> 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.


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.


----------



## Kreij (Apr 5, 2012)

thepollock89 said:


> 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.



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?"


----------



## dick123 (Apr 19, 2012)

Great post so thanks its a very helpful.


----------



## Aquinus (Apr 19, 2012)

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.


```
#!/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
```


----------

