开发者

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?


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

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


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


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

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


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

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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜