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

3

6

Given the following file, where line 1 is blank:

\n
Line 2\n
Line 3\n

How would you output only "Line 2" using sed?

Solutions using other standard UNIX tools, for example awk, are welcome.

Nowak answered 6/5, 2015 at 9:57 Comment(0)
S
1

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

Shelter answered 12/7, 2017 at 12:40 Comment(0)
C
11

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
Crony answered 6/5, 2015 at 10:8 Comment(2)
awk 'NF{print;exit}' would also work depending on whether they count whitespace as blank or not.Uncommercial
The non-standard -m extension was added to OpenBSD's grep(1) on Dec 9, 2017. Nice. Even more simple than sed.Nowak
N
4

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
Nowak answered 6/5, 2015 at 9:57 Comment(3)
I would probably have said sed '/./q;d' file, but either works.Cureall
@Wintermute, very nice. I did not realize the line would be echoed before quitting.Nowak
It will if the -n option is not given to sed. q is similar to n in this regard. This behavior can be used nicely in this case, but to be honest, it is vexing more often than not. GNU sed has a Q command that quits without printing regardless of -n because of this.Cureall
S
1

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

Shelter answered 12/7, 2017 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.