如何使用 sed 只打印第一行非空行
How to print only the first non-blank line using sed
给定以下文件,其中第 1 行为空白:
\n
Line 2\n
Line 3\n
如何使用 sed 只输出 "Line 2"?
欢迎使用其他标准 UNIX 工具(例如 awk)的解决方案。
带注释的多行版本
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
使用带有 -m
开关的 grep 版本,例如 GNU or OpenBSD grep:
grep -m 1 . file
这会在 1 个匹配行后停止读取文件。 .
匹配任何字符,因此第一个非空行将匹配。
使用任意版本的awk(与sed版本基本相同):
awk '/./{print;exit}' file
如果您有一个空行,这些示例有效,但如果您有一个包含 space 或制表符等字符的行,则这些示例无效。
我认为即使 "blank" 行包含 space 或制表符,此版本也能正常工作。
sed '/[^[:blank:]]/q;d' file
给定以下文件,其中第 1 行为空白:
\n
Line 2\n
Line 3\n
如何使用 sed 只输出 "Line 2"?
欢迎使用其他标准 UNIX 工具(例如 awk)的解决方案。
带注释的多行版本
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
使用带有 -m
开关的 grep 版本,例如 GNU or OpenBSD grep:
grep -m 1 . file
这会在 1 个匹配行后停止读取文件。 .
匹配任何字符,因此第一个非空行将匹配。
使用任意版本的awk(与sed版本基本相同):
awk '/./{print;exit}' file
如果您有一个空行,这些示例有效,但如果您有一个包含 space 或制表符等字符的行,则这些示例无效。
我认为即使 "blank" 行包含 space 或制表符,此版本也能正常工作。
sed '/[^[:blank:]]/q;d' file