Jill448
Jill448

Reputation: 1793

shell script grep to grep a string

The output is blank fr the below script. What is it missing? I am trying to grep a string

#!/bin/ksh    
file=$abc_def_APP_13.4.5.2    
if grep -q abc_def_APP $file; then
 echo "File Found"
else
 echo "File not Found"
fi

Upvotes: 5

Views: 32558

Answers (2)

glenn jackman
glenn jackman

Reputation: 247250

Yuck! Use the shell's string matching

if [[ "$file" == *abc_def_APP* ]]; then ...

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 755114

In bash, use the <<< redirection from a string (a 'Here string'):

if grep -q abc_def_APP <<< $file

In other shells, you may need to use:

if echo $file | grep -q abc_def_APP

I put my then on the next line; if you want your then on the same line, then add ; then after what I wrote.


Note that this assignment:

file=$abc_def_APP_13.4.5.2

is pretty odd; it takes the value of an environment variable ${abc_def_APP_13} and adds .4.5.2 to the end (it must be an env var since we can see the start of the script). You probably intended to write:

file=abc_def_APP_13.4.5.2

In general, you should enclose references to variables holding file names in double quotes to avoid problems with spaces etc in the file names. It is not critical here, but good practices are good practices:

if grep -q abc_def_APP <<< "$file"
if echo "$file" | grep -q abc_def_APP

Upvotes: 10

Related Questions