How to print only the first non-blank line using sed How to print only the first non-blank line using sed shell shell

How to print only the first non-blank line using sed


Using a version of grep with the -m switch, such as GNU or OpenBSD grep:

grep -m 1 . file

This stops reading the file after 1 matching line. . matches any character, so the first non-empty line will match.

Using any version of awk (essentially the same as the sed version):

awk '/./{print;exit}' file


Multi-line version with comments

sed -n '  # use -n option to suppress line echoing  /./ {   # match non-blank lines and perform the enclosed functions          # print the non-blank line, i.e., "Line 2"          p          # quit right after printing the first non-blank line          q      }' file

Single-line version without comments

sed -n '/./{p;q;}' file


The examples work if you have an empty line, but not if you have a line containing characters like space or tab.

I think this version would work even if the "blank" line contains spaces or tabs.

sed '/[^[:blank:]]/q;d' file