Waffles
Waffles

Reputation: 11

How would I use grep on a single word in UNIX?

I want to run a script in unix that will look for a specific pattern inside a passed argument. The argument is a single word, in all cases. I cannot use grep, as grep only works on searching through files. Is there a better unix command out there that can help me?

Upvotes: 0

Views: 853

Answers (6)

loganaayahee
loganaayahee

Reputation: 819

my File is:

$ cat > log 
loga

hai how are you loga

hai

hello

loga

My command is:

sed -n '/loga/p' log

My answer is:

loga

hai how are you loga

loga

Upvotes: 0

Alex Jasmin
Alex Jasmin

Reputation: 39516

Depending on what you're doing you may prefer to use bash pattern matching:

# Look for text in $word
if [[ $word == *text* ]]
then
  echo "Match";
fi

or regular expressions:

# Check is $regex matches $word
if [[ $word =~ $regex ]]
then
  echo "Match";
fi

Upvotes: 2

dogbane
dogbane

Reputation: 274878

if echo $argument | grep -q pattern
then
    echo "Matched"
fi

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 343181

you can use case/esac as well. No need to call any external commands (for your case)

case "$argument" in
  *text* ) echo "found";;
esac

Upvotes: 1

jamihash
jamihash

Reputation: 1900

As of bash 3.0 it has a built in regexp operator =~

Checkout http://aplawrence.com/Linux/bash-regex.html

Upvotes: 0

atk
atk

Reputation: 9324

Grep can search though files, or it can work on stdin:

$ echo "this is a test" | grep is
this is a test

Upvotes: 4

Related Questions