Remove empty lines and lines containing only whitespace from notes.txt.
Leave lines with other content unchanged.
Which command is appropriate?
sed with the whitespace-only address and d command deletes matching pattern spaces before they are printed.
Detailed explanation
sed '/^[[:space:]]*$/p' notes.txtIncorrect. p prints matching lines in addition to the default output.
Incorrect. p adds output; without -n it can duplicate the selected lines.
sed '/^$/d' notes.txtIncorrect. ^$ matches only truly empty lines, not whitespace-only lines.
Incorrect. ^$ matches only a truly empty line and leaves spaces or tabs.
sed '/^[[:space:]]*$/d' notes.txtCorrect. The pattern covers empty and whitespace-only lines, and d deletes them.
Correct. The address matches zero or more whitespace characters and d removes those lines.
grep -v '^$' notes.txtIncorrect. grep -v '^$' leaves whitespace-only lines.
Incorrect. grep -v '^$' excludes only empty lines, not whitespace-only lines.
Try it yourself
An example you can run in a temporary verification environment.
printf 'alpha\n \n\nbeta\n' | sed '/^[[:space:]]*$/d'Expected result
alpha
betaKey points
- [[:space:]] matches whitespace
- * permits zero or more
- sed d deletes the current line
Notes
- Environment: GNU sed 4.x / C.UTF-8ロケール
- Use temporary files and harmless commands for pattern experiments.
- Regular-expression details should be checked against the target GNU implementation.
Foundation review
Place the condition
Combining a whitespace-only address with d removes both empty and whitespace-only lines without changing other lines.
Check the result
Use input containing an empty line and a line containing spaces, then inspect the remaining lines.