bash - unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件

标签 bash shell unix grep

我想要一个 unix 命令来查找单词第一次出现和最后一次出现之间的行

例如:

假设我们有 1000 行。第十行包含单词“stackoverflow”,第五三十行也包含单词“stackoverflow”。

我想打印 10 到 35 之间的行并将其写入新文件。

最佳答案

您可以分两步完成。基本思想是:

1) 获取第一个和最后一个匹配的行号。

2) 打印这些范围之间的行范围。

$ read first last <<< $(grep -n stackoverflow your_file | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
$ awk -v f=$first -v l=$last 'NR>=f && NR<=l' your_file

说明

  • read first last读取两个值并将它们存储在 $first 中和 $last .
  • grep -n stackoverflow your_file greps 并显示如下输出:number_of_line:output
  • awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')打印 stackoverflow 的第一个和最后一个匹配项的行数在文件中。

  • awk -v f=$first -v l=$last 'NR>=f && NR<=l' your_file打印来自 $first 的所有行行号直到 $last行号。

测试

$ cat a
here we
have some text
stackoverflow

and other things
bla
bla
bla bla
stackoverflow
and whatever else
stackoverflow
to make more fun
blablabla

$ read first last <<< $(grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')
$ awk -v f=$first -v l=$last 'NR>=f && NR<=l' a
stackoverflow

and other things
bla
bla
bla bla
stackoverflow
and whatever else
stackoverflow

按步骤:

$ grep -n stackoverflow a
3:stackoverflow
9:stackoverflow
11:stackoverflow

$ grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}'
3 11

$ read first last <<< $(grep -n stackoverflow a | awk -F: 'NR==1 {printf "%d ", $1}; END{print $1}')

$ echo "first=$first, last=$last"
first=3, last=11

关于bash - unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19496420/

相关文章:

macos - 如何删除 shell 可执行文件的停靠图标?

unix - 将 file2 中第一列中的模式替换为 file1 中 file2 中第二列中的模式

postgresql - 在 PostgreSQL 中创建用户 sudo : unknown user

linux - 不断检查辅助硬盘驱动器是否出现故障

bash - 删除每第 n 行的最后一个字符

linux - 在 awk 命令中使用变量

regex - grep -v pattern 并删除之前的 1 行和之后的 4 行

c - 在 C 中实现命令行解释器,特殊情况

linux - 如何使用带有管道概念的排序和复制命令?

linux - Unix/Linux Shell Grep 来切