Grep through a variable

I want to search a text in file but that file is pointing to variable.
ex:

file=there was nothing special
grep "there was nothing" $file

but its not working . Can u let me know that how we can use variable($file) in grep command.

Nothing AIX specific - moving thread.

grep searches in file. You are creating a variable called file (thats why you are putting $ in the front) - its not the same thing.

You don't need grep here (at least not in this specific case):

% file='there was nothing special'                       
% case $file in ( *"there was nothing"* ) echo bingo;; esac
bingo

Actually the query is,
In the variable $file, report name is coming.

file=/u01/app/oracle/admin/tools/ADDM4CMSAU2T_p19846dev133_111011_1_30_2_30.txt

but i want to check the string in that file but my query is not working in the script.

query:

ADDM=`ls |grep "THERE WAS NOT ENOUGH DATABASE TIME FOR ADDM ANALYSIS" $file | awk 'BEGIN {FS=":"}{print $1}'`
echo $ADDM
for aADDM in ${ADDM}
  do
echo $aADDM
    rm $aADDM
echo $aADDM
      echo "Info: Removing the file $aADDM since there is not enough database time for addm analysis..." >> $LogFile
      done

You should provide a sample of the contents of $file which show the string "THERE WAS NOT ENOUGH DATABASE TIME FOR ADDM ANALYSIS". Also, I think you should check the basic usage of grep; your code is way off from the basic usage.

There are a few problems with your code:

First off, using backticks is deprecated, outdated, not recommended and (in an ideal world) prohibited by law. Seriously: it is only supported for backward compatibility. Don't use it. Use the "$(...)" instead.

ADDM="$(ls |grep "THERE WAS NOT ENOUGH DATABASE TIME FOR ADDM ANALYSIS" $file | awk 'BEGIN {FS=":"}{print $1}')"

Second: what is your "grep" supposed to do? As you have written it, it filters the output of "ls" and i do not think this is what is intended.

Third: you have to decide either to have "grep" work in a pipeline or over a file. You can't have both, as you have written:

grep "some_regex" /path/to/some/file   # this is ok
some_process | grep "some_regex"      # this is ok too
some_process | grep "some_regex" /some/file    # this won't work

Fourth: This doesn't need to be an error, but i suppose it might be one. Do you really want to search for some all-caps text? If so, then all is ok, otherwise you might want to use the "-i" switch (case-insensitive search mode) for grep.

Fifth: you use awk to further work on lines found. You could probably do what your "grep" does inside awk if you use it anyways, because awk can work on select lines as well.

I hope this helps.

bakunin

1 Like