linux - Grep 查找行号后的下一个空行

标签 linux shell sed grep

我有一个大文件,其中包含不同制表符分隔数据的表格。不同的表格由空行分隔。

我有特定表格开头的行号,我需要检索整个表格。

如何使用 grep(或类似工具)获取特定行号后的下一个空行的行号?

最佳答案

为此使用 sed,这应该可以解决问题:

sed -n '1,/^\s*$/p' file

只需替换逗号前的第一个数字,在本例中 1 为行号,演示从给定行号打印每个表:

$ cat file
one
two
three

five
six
seven

nine
ten
eleven

$ sed -n '1,/^\s*$/p' file
one
two
three

$ sed -n '5,/^\s*$/p' file
five
six
seven

$ sed -n '9,/^\s*$/p' file
nine
ten
eleven

使用 -n 选项关闭每行的默认打印和 p 标志 sed 从行号到第一行打印与正则表达式匹配的行,其中:

^     # Matches the start of the line
\s*   # Matches zero or more whitespace characters
$     # Matches the end of the line

使用格式 sed -n 'A,Bp' 其中 AB 可以是行号或可以打印的正则表达式文件的小节很容易。

要使用 sed 仅打印下一个空白行的行号,请执行以下操作:

$ sed -n '1,/^\s*$/{=}' file | tail -1
4

$ sed -n '5,/^\s*$/{=}' file | tail -1
8

$ sed -n '9,/^\s*$/{=}' file | tail -1
12

或者只打印所有空白行所在的位置

$ sed -n '/^\s*$/{=}' file
4
8
12

使用 awk 获取下一个空白行号不需要使用 tail:

$ awk 'NR>=1 && /^\s*$/{print NR;exit}' file
4

$ awk 'NR>=5 && /^\s*$/{print NR;exit}' file
8

$ awk 'NR>=9 && /^\s*$/{print NR;exit}' file
12

$ awk '/^\s*$/{print NR}' file
4
8
12

如果它让您更清楚,您可以使用 -v 将变量传递给 awk

$ awk -v start=1 'NR>=start && /^\s*$/{print NR;exit}' file
4

$ awk -v start=5 'NR>=start && /^\s*$/{print NR;exit}' file
8

$ awk -v start=9 'NR>=start && /^\s*$/{print NR;exit}' file
12

关于linux - Grep 查找行号后的下一个空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14275200/

相关文章:

带重定向的 shell 内置

regex - 查找给定字符串后的第一个字符

shell - 意外地用 sed 替换 &

c++ - 运行程序时如何捕获输入和输出到文件?

linux - fish shell 和 ssh 远程命令的问题

linux - 如何在 shell 中执行 ssh 时更改文件权限

bash - sed:删除除最后 n 个字符之外的所有字符

linux - 不能打开超过 1023 个套接字

linux - Linux bash 脚本中的 Perl 脚本

linux - 每秒通过 linux 将文件从 FTP 移动到本地