1

I have to go through some regular files in directories and find those files, that have their own name in its content.

In the following piece of script is a cycle in which I am going through paths and using grep to find the file's name in its content. What is surely correct is $something:q - is array of paths where i have to find files. The next variable is name in which is only name of current file. for example: /home/computer/text.txt (paths) and: text.txt (name)

And my biggest problem is to find names of files in their content. It's quite difficult for me to write correct grep for this, cause the names of files and directories that I am passing through are mad. Here are some of them:

/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/!_1
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/dam/$user/:e/'/-r
/home/OS/pocitacove/testovaci_adresar/z/test3/skusime/ taketo/   taketo
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/.a=b
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/@
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/:
/home/OS/pocitacove/testovaci_adresar/z/test4.pre_expertov/.-bla/.-bla/'ano'

foreach paths ($something:q)
    set name = "$paths:t"
    @ number = (`grep -Ec "$name" "$paths"`)

    if ($number != 0) then
        echo -n "$paths "
        echo $number
    endif

    @ number = 0
end
  • How are you getting the paths, if you could manage to do this using find -exec grep "{}" "{}"\; it would probably solve all your problems. – terdon Oct 26 '13 at 17:34
1

If I understand you correctly, your problem is that your file names are getting interpreted as regex metacharacters. In that case, you want the -F switch to grep (which is specified by POSIX). It tells grep to interpret its pattern as a fixed string rather than a regex:

@ number = (`grep -Fc -- "$name" "$paths"`)

Note also the addition of -- to specify "end of options" to grep to get around file names starting with -. Note also that the -E switch, which enables extended regular expressions, is no longer needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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