views:

246

answers:

1

Hello,

i want that my bash script does the following:

It finds a file, for example: hello.txt

It searches for a specific text in the file, for example: hey

If it is found, continue to the next thing,

if it isn't found, write the text on a new line & continue to the next thing.

Can anyone give me the script for this?

EDIT: Also i would like to do this more times in a row, so something time-saving would be great!

+2  A: 

First, in reply to your comments:

But i'm a newbie in bash, i did some tutorial, and it helped me, but it doesnt explain how to do this stuff.

Then you probably did the wrong tutorial. The Bash Beginners Guide at TLDP should be able to help you.

i did work a long time with batch (windows). There i needed sed for this. Are you going to need a special tool too for bash?

Yes, but they all are standard on most Unix systems (including Mac OS X, I guess).

can anyone give an answer?

Since I'm in a good mood today...

grep is used to search for text in files.

echo and redirection (> >> < |) work the same in bash as they do in Windows' cmd.exe, so you probably already know how to use these.

#!/bin/bash
...
# The 'if ! grep ...' part is probably the hardest.
if ! grep "hey" "$filename" &> /dev/null; then
    # "hey" was not found - use 'echo' to add it
fi
...

The rest you should figure out yourself.

grawity
Thanks! This works. Yeah, i already understand 'echo hey >>filename'
YourComputerHelpZ