Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file named input.txt with this contents:

...
FILE "Edie - Realities.txt" TXT
...

And I want to read it, then strip filename path from line that starts with FILE, and check if it exists, so:

[ -f $(cat input.txt | grep FILE | grep -o "\".*\"") ] && echo "exist" || echo "does not exist"

but this outputs:

[: too many arguments  
does not exist

If I run:

echo $(cat input.txt | grep FILE | grep -o "\".*\"")

I get what I expected:

"Edie - Realities.txt"

So why is this, or how can I solve this problem?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

$(...) is evidently passing "Edie, -, and Realities.txt" as separate arguments. You need to quote $(...) like any other $variable, and you probably want to remove the "s.

[ -f "$(cat input.txt | grep FILE | sed 's/^.*"\(.*\)".*$/\1/')" ] && echo "exist" || echo "does not exist"
share|improve this answer
    
Thanks. Marking first answer, as both are correct –  zetah Mar 1 '12 at 16:21
add comment

You need to quote the argument to -f -- if you run with set -x you'd see the command being performed is [ -f '"Edie' '-' 'Realities.txt"' ] which is too many arguments.

[ -f "$(sed -e '/FILE/!d' -e 's/FILE "\([^"]*\).*/\1/' input.txt)" ]

If you have GNU grep on your system, you can use:

[ -f "$(grep -Po '(?<=FILE ").*(?=")' input.txt)" ] 
share|improve this answer
add comment

For your file contents

FILE "/path_to_file/filename" TXT

do something like

grep FILE  input.txt | while read line 
  do
    fname=`echo $line | awk -F\" '{print $2}'`  # this separates the line by the quotes
                                                # result is like /path_to_file
    echo $fname # just to check it 
    if [ -f $fname ]
    then
      ls -l $fname
      echo "file exists"
    else
      echo "no file there $file"
    fi
  done
share|improve this answer
1  
No. You missed the crucial point that $fname must be in double quotes. The rest of your code isn't particularly helpful here. –  Gilles Mar 1 '12 at 23:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.