noob_coder
noob_coder

Reputation: 829

unix command to grep for a particular word in a file

i have a file that has a pattern like this

String(`TYPE',`ABC')dnl 
String('TYPE',`BCD')dnl

and some other similar lines, so here i want this line String(TYPE',ABC')dnl i am using this command

cat file | grep TYPE

which gives me the desired output but when i am using the same command inside one script it throws one error

`cat file | grep TYPE`
-bash: define(`TYPE',`ABC')dnl: command not found

what is that i need to modify in my command ?

Upvotes: 1

Views: 3449

Answers (2)

cdarke
cdarke

Reputation: 44444

The problem is that the output from grep is being executed as a command because of the back-ticks.

First, you don't need the external program cat, grep takes the input filename as a parameter. Second, it is wise to always enclose a pattern you are looking for in single quotes, to protect it from the shell. In this case it is not strictly required, but it is a good habit to get into:

grep 'TYPE' file

Now, that command will write the result to standard-output (the screen). If you want it stored in a variable then use the $( ) notation rather than the deprecated back-ticks:

 var=$(grep 'TYPE' file)

now you can do what you like with $var.

You say you want the "word" TYPE. What if you had this line in your file:

String(`UNTYPELESS',`ABC')dnl 

Your search for TYPE would pick that up as well! If you want to check for word boundaries you can use egrep:

egrep '\bTYPE\b' file

The \b indicates that a word-boundary (essentially any non-alpha, or beginning of text or end-of-text) must exist at that point in the pattern.

Upvotes: 1

Kent
Kent

Reputation: 195269

  • you don't need the cat
  • You put shell cmd in back-ticks, the result of the cmd will be executed as new command, that's why you have the error msg
  • If you just want to see the result, just grep 'TYPE' file
  • If you want to assing the result to some var, RESULT="$(grep 'TYPE' file)"

Upvotes: 0

Related Questions