Assuming a directory structure like the following:
A
|-- B
| |-- file1.out
| |-- file2.out
| `-- file3.out
|-- C
| |-- file1.out
| |-- file2.out
| `-- file3.out
|-- D
| |-- file1.out
| |-- file2.out
| `-- file3.out
`-- E
|-- file1.out
|-- file2.out
`-- file3.out
The issue with your code is that your grep will produce output that looks like
./B/file1.out:2:some data which includes the word index123
./B/file2.out:2:some data which includes the word index123
./B/file3.out:2:some data which includes the word index123
./C/file1.out:2:some data which includes the word index123
./C/file2.out:2:some data which includes the word index123
./C/file3.out:2:some data which includes the word index123
./D/file1.out:2:some data which includes the word index123
./D/file2.out:2:some data which includes the word index123
./D/file3.out:2:some data which includes the word index123
./E/file1.out:2:some data which includes the word index123
./E/file2.out:2:some data which includes the word index123
./E/file3.out:2:some data which includes the word index123
That is the output of
grep --include=\*.out -rnw . -e "index123"
with A as the current directory.
You will then try to run basename on these individual lines, which fails since basename takes at most two arguments (a pathame and a suffix to strip from that pathname). GNU basename will complain about an "extra operand" while BSD basename will complain about incorrect usage.
grep will show you the names of the files (only, i.e. not the complete line that matched) when you use it with the -l flag.
This means that your script may be replaced by the single command
grep -w -l "index123" */*.out
This will give output on the form
B/file1.out
B/file2.out
B/file3.out
C/file1.out
C/file2.out
C/file3.out
D/file1.out
D/file2.out
D/file3.out
E/file1.out
E/file2.out
E/file3.out
I added -w as you used in your grep command line. -n (for numbering lines, which you are also using) may not be used together with -l.
Judging from your code, this is what you want.
If you need just the folder names, then do
$ grep -w -l "index123" */*.out | sed 's#/[^/]*##' | sort -u
B
C
D
E
All of this assumes that A is the current working directory, but you said that this was the case in the question so it shouldn't be a problem.
/../A? – Kusalananda Apr 11 '18 at 19:02grep index123 */*.out– Jeff Schaller Apr 11 '18 at 19:07grep -lto get the filenames – Jeff Schaller Apr 11 '18 at 19:08index123 */*.outbefore while|? If so, it shows no such file or directory – Akand Apr 11 '18 at 20:04grep -l index123 */*.outis the complete command. – Kusalananda Apr 11 '18 at 20:18