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.
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.
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
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
-m
extension was added to OpenBSD's grep(1) on Dec 9, 2017. Nice. Even more simple than sed. –
Nowak 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
sed -n '/./{p;q;}' file
sed '/./q;d' file
, but either works. –
Cureall -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 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
© 2022 - 2024 — McMap. All rights reserved.
awk 'NF{print;exit}'
would also work depending on whether they count whitespace as blank or not. – Uncommercial