From config.txt, remove blank or whitespace-only lines and comments whose first non-space character is #.
Display only the remaining configuration lines.
Which command is appropriate?
Combine the two excluded forms in an ERE and invert the match with grep -v. Include leading whitespace before a comment marker.
Detailed explanation
grep -E '^[[:space:]]*(#|$)' config.txtIncorrect. It prints the lines to be excluded rather than removing them.
Incorrect. It prints the lines to be excluded rather than removing them.
grep -v '^#' config.txtIncorrect. It misses comments preceded by spaces and does not exclude blank lines.
Incorrect. It misses comments preceded by spaces and does not exclude blank lines.
grep -v '^[[:space:]]*$' config.txtIncorrect. It excludes blank lines but leaves comment lines in the output.
Incorrect. It excludes blank lines but leaves comment lines in the output.
grep -Ev '^[[:space:]]*(#|$)' config.txtCorrect. It matches both excluded forms and -v prints everything else.
Correct. It matches both excluded forms and -v prints everything else.
Try it yourself
An example you can run in a temporary verification environment.
printf '%s\n' '# one' ' # two' '' 'key=value' | grep -Ev '^[[:space:]]*(#|$)'Expected result
key=valueKey points
- -v inverts the match
- Account for leading whitespace
- Represent blank lines with $
Notes
- Environment: GNU grep 3.x / LC_ALL=C
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.