I have a text file infile.txt that contains the following string:
[ A ]
1
2
[ B ]
3
[ C
4
5 
[ D ]
I wish to use both grep and sed to print the lines that start with [ and end with ]. Thus my desired output from grep and sed is:
[ A ]
[ B ]
[ D ]
As a reality check, I will first try to print the lines that contain [:
grep "\[" infile.txt
grep -E "\[" infile.txt
sed -n '/\[/p' infile.txt
sed -nE '/\[/p' infile.txt
Each of the preceding commands gives this output:
[ A ]
[ B ]
[ C
[ D ]
Now I need to specify that the printed lines should start with [ and end with ]. This answer to this question suggests using the regular expression \[[^\]]*\]. However, all of the following commands give no output (empty string):
grep "\[[^\]]*\]" infile.txt
grep -E "\[[^\]]*\]" infile.txt
sed -n '/\[[^\]]*\]/p' infile.txt
sed -nE '/\[[^\]]*\]/p' infile.txt
But each of the following commands...
grep "\[*\]" infile.txt
grep -E "\[*\]" infile.txt
sed -n '/\[*\]/p' infile.txt
sed -nE '/\[*\]/p' infile.txt
...give the desired output:
[ A ]
[ B ]
[ D ]
Why doesn't the regular expression \[[^\]]*\] -- again, from this answer to this question -- work for my text?

