4

Did this million times already, but this time it's not working I try to grep "$TITLE" from a file. on command line it's working, "$TITLE" variable is not empty, but when i run the script it finds nothing

*title contains more than one word

echo "$TITLE"
cat PAGE.$TEMP.2 | grep "$TITLE"

what i've tried:

echo "cat PAGE.$TEMP.2 | grep $TITLE"

to see if title is not empty and file name is actually there

3
  • 1
    Have you actually tried to grep the file with the value? Maybe the title really isn't in the file. Commented Sep 6, 2012 at 10:18
  • yes i tried, it's there 100%. i even took the output of echo "cat PAGE.$TEMP.2 | grep $TITLE" and run it Commented Sep 6, 2012 at 10:22
  • 1
    But the first time you had quotes around the "$TITLE", the second time you don't. Commented Sep 6, 2012 at 10:42

4 Answers 4

5

Are you sure that $TITLE does not have leading or trailing whitespace which is not in the file? Your fix with the string would strip out whitespace before execution, so it would not see it.

For example, with a file containing 'Line one':

/home/user1> TITLE=' one '
/home/user1> grep "$TITLE" text.txt
/home/user1> cat text.txt | grep $TITLE
Line one

Try echo "<$TITLE>", or echo "$TITLE"|od -xc which sould enable you to spot errant chars.

Sign up to request clarification or add additional context in comments.

1 Comment

WORKED! thanks man! od -xc helped me, great tool. i added tr -d '\r\n\' and that fixed the problem.
2

This command

echo "cat PAGE.$TEMP.2 | grep $TITLE"

echoes a string that starts with 'cat'. It does not run a command. You would want

echo "$( cat PAGE.$TEMP.2 | grep $TITLE )"

although that is identical in functionality to the simpler

cat PAGE.$TEMP.2 | grep $TITLE

And as pointed out by others, there is no need to pipe a single file using cat; grep can read from files just fine:

grep "$TITLE" "PAGE.$TEMP.2"

(Your default behavior should be to quote parameter expansions, unless you can show it is incorrect to do so.)

Comments

0

Works for me:

~> cat test.dat
abc
cda
xyz
~> export GRP=cda
~> cat test.dat | grep $GRP
cda

Edit:

Also the proper way to use grep is:

~> grep $GRP test.dat

Comments

0

I had similar problem yet it was caused by '~' in the path not being expanded correctly. I needed to use $HOME instead within the bash script. Then all good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.