如何逐行计算单词的行数,其中 word2 -bash
How to count lines with word after line where is word2 -bash
我有一个大文本文件,其中一些行包含单词 "DataMeetingIs11"
,而下一行包含单词 "done"
。我的任务是计算所有这些行。例如我想计算以下内容:
......DataMeetingIs11.....
....done..................
但不包括以下内容:
......DataMeetingIs11.....
..........................
我尝试使用下一个命令:
grep -A 1 DataMeetingIs11 file| grep -c done
但是没有用。你能帮帮我吗?
编辑
我如何计算没有 "done" 个单词的行数?
您可以改用 awk:
awk '/DataMeetingIs11/ {a++; p=NR} /done/ && NR==(p+1) {c++}
END{print "Without done:", (a-c) ", With done:", c}' file
Without done: 1, With done: 2
解释:
/DataMeetingIs11/ # when input line matches literal "DataMeetingIs11"
{a++; p=NR} # store current line # NR into variable p and increment a
/done/ && NR==(p+1) # when line matches "done" and when
# current line # is p+1 (next line)
{c++} # increment a counter c
END{print (a-c), c} # print counts the end
如果您知道(从您的数据结构),单词 'done' 不会出现在与 DataMeetingIs11 相同的行上,这也应该有效(前提是您有 Gnu grep,以便-识别标志):
fgrep -A 1 DataMeetingIs11 your_file|fgrep -c done
另一种假设文件将作为一个整体装入内存的可能性是 Perl:
perl -n -l -w -0777 -e 'print scalar(()=/DataMeetingIs11.*\n.*done/g)' your_file
-0777 "Perl Magic" 将整个文件作为单个字符串传送,而不是逐行处理。
-n 注意文件内容存储在 Perl 的 "magic variable" $_
Regexp 匹配您要查找的内容,修饰符 'g' 告诉 Perl 尽可能频繁地匹配它。
'()=' 将正则表达式放入所谓的 "list mode"。列表模式的正则表达式 returns 匹配列表。
'scalar(...)' 运算符在列表中的元素数量中转换列表,然后将其打印到标准输出。
-l 确保之后打印换行符。
我有一个大文本文件,其中一些行包含单词 "DataMeetingIs11"
,而下一行包含单词 "done"
。我的任务是计算所有这些行。例如我想计算以下内容:
......DataMeetingIs11.....
....done..................
但不包括以下内容:
......DataMeetingIs11.....
..........................
我尝试使用下一个命令:
grep -A 1 DataMeetingIs11 file| grep -c done
但是没有用。你能帮帮我吗?
编辑
我如何计算没有 "done" 个单词的行数?
您可以改用 awk:
awk '/DataMeetingIs11/ {a++; p=NR} /done/ && NR==(p+1) {c++}
END{print "Without done:", (a-c) ", With done:", c}' file
Without done: 1, With done: 2
解释:
/DataMeetingIs11/ # when input line matches literal "DataMeetingIs11"
{a++; p=NR} # store current line # NR into variable p and increment a
/done/ && NR==(p+1) # when line matches "done" and when
# current line # is p+1 (next line)
{c++} # increment a counter c
END{print (a-c), c} # print counts the end
如果您知道(从您的数据结构),单词 'done' 不会出现在与 DataMeetingIs11 相同的行上,这也应该有效(前提是您有 Gnu grep,以便-识别标志):
fgrep -A 1 DataMeetingIs11 your_file|fgrep -c done
另一种假设文件将作为一个整体装入内存的可能性是 Perl:
perl -n -l -w -0777 -e 'print scalar(()=/DataMeetingIs11.*\n.*done/g)' your_file
-0777 "Perl Magic" 将整个文件作为单个字符串传送,而不是逐行处理。
-n 注意文件内容存储在 Perl 的 "magic variable" $_
Regexp 匹配您要查找的内容,修饰符 'g' 告诉 Perl 尽可能频繁地匹配它。
'()=' 将正则表达式放入所谓的 "list mode"。列表模式的正则表达式 returns 匹配列表。
'scalar(...)' 运算符在列表中的元素数量中转换列表,然后将其打印到标准输出。
-l 确保之后打印换行符。