What's in B.txt? What's in file.txt?
The "echo $a" is useless, since you've told grep to look inside file.txt, not standard input. I'm not sure what its purpose was intended to be.
$a.txt should work just as well as $a\.txt.
Quote:
I always get that no such file or directory exists for any $a.txt
What do you mean? The script prints those messages? Or that it doesn't create the files you want?
If $a is ever a string with spaces in it, it will split on those spaces, which will cause the string
search string with spaces to make grep look for the string
search inside the files "string", "with", "spaces", and "file.txt"
Quote it like "$a" to prevent it splitting.