grepでコメント行と空白を除外する

grepでコメント行と空白を除外する場合、以下のようにすると良いだろう。

grep -v -e '^$' -e '^#' 対象のファイル

一応解説をすると、-vで検索条件に該当する行を除外して出力するよ、という意味。
-eで複数の条件で検索するという意味で、'^$'は正規表現で行頭に行末が来ている場合、'^#'で行頭にコメントアウトがある場合を指定している。

実際に、crontabで実行した結果がこちら。

$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
*/5 * * * * root /usr/local/bin/update_motd.sh
[root@test-centos ~]#
[root@test-centos ~]# grep -v -e '^$' -e '^#' /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
*/5 * * * * root /usr/local/bin/update_motd.sh
$