首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用于计算除#之外的部分中的行数的脚本

用于计算除#之外的部分中的行数的脚本
EN

Stack Overflow用户
提问于 2017-07-25 21:18:52
回答 4查看 46关注 0票数 0

我正在寻找可以让脚本执行以下操作的想法:

我有一个文本文件,例如。包含类似文本的test.txt

代码语言:javascript
复制
#
# sectione 1
#
several
text
lines 
and so on
#
# sectione 2
#
more text
and more
#
and more
# ...
#
# sectione 3
#
more
more
more 
#
# sectione 4
#
...
...

我需要一个可能性,只计算第二部分中的行,并排除以#开头的行

在我上面的例子中,脚本应该向我显示一个计数器,末尾有"3“,例如。

代码语言:javascript
复制
# counter_script.sh test.txt 
# 3

这是可能的吗?我该怎么做呢?我使用的是带有bash shell的Debian Linux。

EN

回答 4

Stack Overflow用户

发布于 2017-07-25 22:06:56

您可以使用以下awk命令:

代码语言:javascript
复制
awk '/sectione/{f=$3==2?1:0}f&&!/^#/{c++}END{print c}' file

多行版本中的解释:

2.awk:

代码语言:javascript
复制
/sectione/ {
    # Set f(ound) to 1 (true) if the number between 'sectione' is a 2
    # otherwise 0 (false)
    f=$3==2?1:0
}

# If f(ound) is true (1) and the line starts not with a #
# count it
f&&!/^#/{
    c++
}

# At the end of input print the c(ount)
END{
    print c
}
票数 1
EN

Stack Overflow用户

发布于 2017-07-25 21:30:37

下面的代码将只查找(sectione 2)节计数。试着关注并让我知道这是否有帮助。

代码语言:javascript
复制
awk '/sectione 3/{a=""}/sectione 2/{a=1;next} !/#/ && a{count++} END{print count}'   Input_file

EDIT1:现在也在同一个平台上增加了一个解决方案。

代码语言:javascript
复制
awk '/sectione 2/,/sectione 3/{count=$0!~/#/?++count:count} END{print count}'   Input_file
票数 0
EN

Stack Overflow用户

发布于 2017-07-25 21:55:44

另一种方法:

代码语言:javascript
复制
sed -n '/# sectione 2/,/# sectione 3/{/^#/d;//!p;}' file | wc -l

/# sectione 2/,/# sectione 3/选择第2节和第3节之间的线

/^#/d删除以#开头的行

//!p打印其余部分..

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45304581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档