0
for i in `ls -l`; do for j in `ls -l /abc`; do cat $j | grep $i;done;done;

I want to search for each filename in pwd with files in abc directory. Please help me in this.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • The above one is not working :( – user2433165 Sep 18 '14 at 15:41
  • Never loop on the output of `ls` in shell, any time you write a shell loop just to parse text it's the wrong approach, you don't need cat with grep (UUOC), and always quote your shell variables unless you have a specific purpose in mind that requires them to be unquoted and fully understand all of the implications. – Ed Morton Sep 18 '14 at 16:21

3 Answers3

0

I guess you want:

for filename in * ; do
    grep -F -- "$filename" /abc/*
done

Note that, due to the nature of grep, this will not work properly if any of your filenames contain newlines. (Fortunately, that's quite rare; but it's something to keep in mind.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Thanks.Thats fine.I want to use two for loops and redirect the output to a file for each file in pwd – user2433165 Sep 18 '14 at 15:49
  • 2
    @user2433165 This answer seems correct to me. If you want to over-complicate your life by creating arbitrary nested loops, that's a self-inflicted injury or a homework assignment. – Todd A. Jacobs Sep 18 '14 at 17:01
0

Something like this would be the right approach IF the files in your pwd cannot contain newlines in their names:

ls |
awk '
NR==FNR{ files[$0]; next }
{
    for (file in files) {
        if ( index($0,file) ) {
            print FILENAME, file
        }
    }
}
' - /abc/*

but, like your grep approach, it's error prone as a file named "the" would match a line containing "then", and it'd report the same match multiple times if it appeared multiple times in a target file. If any of that's an issue update your question to show some sample input and output so we can help you.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

Not really a programming question.. but what about just using find?

find abc -type f -name $filename ..

Even if the above does not do exactly what you want (which is a bit unclear to me), using a nested ls is pretty crazy if you already have a method which is ment to do just that.

man find if you want to learn more about the find command.

To do more with the files you located, you can use the -exec flag to execute something for each found file.

Damien Overeem
  • 4,487
  • 4
  • 36
  • 55