1

I have a scenario like

VAR = `Some command brings the file path name and assigns it to VAR`

For example VAR can have value like /root/user/samp.txt

I want to grep command like

grep HI $VAR 

This doesnt works gives an error saying cannot open /root/user/samp.txt same error when tried cat $VAR.

How to handle this ?

I have given try

echo $VAR | grep HI
grep HI "$VAR"

Using korn shell

glenn jackman
  • 85,964
Adr
  • 11
  • It's unclear what you're asking. Does $VAR contain arbitrary text, or does it contain a filename? Are you surprised about the "cannot open file" error message because it is supposed to be a valid file? – glenn jackman Mar 04 '15 at 19:27
  • Have you test what is in $VAR by echo "$VAR"? – Costas Mar 04 '15 at 19:28
  • This works for me. Is there a permission or non-existence problem with /root/user/samp.txt – Robert Jacobs Mar 04 '15 at 19:32
  • 1
    You have first a permissions problem to solve, completely unrelated to your question... are you trying to access files in /root as a normal user?? Try first the command su and give your root password (or sudo bash, in some Linux distributions)`, you will then be root and you should then fix the access/permission problems... – Ariel Mar 04 '15 at 19:39

3 Answers3

0

I know you asked for grep, but if I understand correctly you want to search the path string for a substring. You can just use == or =~ for that, as in

[[ "$VAR" == *"HI"* ]]     # Does "$VAR" match <stuff>HI<stuff>?

or

[[ "$VAR" =~ "HI" ]]       # Does "$VAR" contain HI?
WAF
  • 373
0

I have a variable to which a path of a file is assigned by a command,

for example

VAR=grep /adr filename - assume my filename has a line like /adr/samp.txt

So when I echo $VAR, it gives me the /adr/samp.txt, but gives an error for cat $VAR or with grep

I resolved this by making VAR=$(grep /adr filename). Then I can do cat $VAR.

I dont know whats wrong with ``

Thanks, Adr

Adr
  • 11
0

WAF's [[ "$VAR" =~ "HI" ]] answer here has a great bash/ksh solution that is probably what you are looking for, but in case somebody is looking for a portable solution, here is how to do this natively within a plain POSIX shell (the base /bin/sh):

[ "$VAR" != "${VAR#*HI}" ]

Be careful, shell pattern syntax (aka "globbing") is different from POSIX regular expression syntax.

This compares the value of $VAR with the ${VAR#*HI} parameter expansion, which implements substring removal to remove anything at its beginning up to the first instance of "HI" (given VAR="OHIO", ${VAR#*HI} would be remove the leading OHI and result in just O. VAR="Hi, I am bob" would be unchanged).

Due to the != comparison, the return value will be true (0) when the two strings differ (meaning "HI" exists in $VAR) and false (1) when they are the same (meaning "HI" does not exist in $VAR).

Adam Katz
  • 3,965