我正在寻找可以让脚本执行以下操作的想法:
我有一个文本文件,例如。包含类似文本的test.txt:
#
# sectione 1
#
several
text
lines
and so on
#
# sectione 2
#
more text
and more
#
and more
# ...
#
# sectione 3
#
more
more
more
#
# sectione 4
#
...
...我需要一个可能性,只计算第二部分中的行,并排除以#开头的行
在我上面的例子中,脚本应该向我显示一个计数器,末尾有"3“,例如。
# counter_script.sh test.txt
# 3这是可能的吗?我该怎么做呢?我使用的是带有bash shell的Debian Linux。
发布于 2017-07-25 22:06:56
您可以使用以下awk命令:
awk '/sectione/{f=$3==2?1:0}f&&!/^#/{c++}END{print c}' file多行版本中的解释:
2.awk:
/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
}发布于 2017-07-25 21:30:37
下面的代码将只查找(sectione 2)节计数。试着关注并让我知道这是否有帮助。
awk '/sectione 3/{a=""}/sectione 2/{a=1;next} !/#/ && a{count++} END{print count}' Input_fileEDIT1:现在也在同一个平台上增加了一个解决方案。
awk '/sectione 2/,/sectione 3/{count=$0!~/#/?++count:count} END{print count}' Input_file发布于 2017-07-25 21:55:44
另一种方法:
sed -n '/# sectione 2/,/# sectione 3/{/^#/d;//!p;}' file | wc -l/# sectione 2/,/# sectione 3/选择第2节和第3节之间的线
/^#/d删除以#开头的行
//!p打印其余部分..
https://stackoverflow.com/questions/45304581
复制相似问题