【问题标题】:Count lines following a pattern from file按照文件中的模式计算行数
【发布时间】:2017-02-01 06:50:35
【问题描述】:

例如,我有一个文件test.json,其中包含一系列包含以下内容的行:

  • header{...}
  • body{...}
  • 其他文字(与其他文字一样)
  • 空行

我想运行一个返回以下内容的脚本

Counted started on : test.json
- headers : 4
- body : 5
- <others>
Counted finished : <time elapsed>

到目前为止,我得到的是这个。

count_file() {
    echo "Counted started on : $1"
    #TODO loop
    cat $1 | grep header | wc -l
    cat $1 | grep body | wc -l
    #others
    echo "Counted finished : " #TODO timeElapsed
}

编辑:

编辑问题并添加代码sn-p

【问题讨论】:

  • 显示实际文件的一些片段
  • “预期结果”不应该是您对回答您问题的人的期望(这表明您目前没有付出任何努力)。它应该是您期望的输出
  • 你可以简单地使用cat $1 |grep header |... 而不是grep header $1 |...

标签: shell unix grep


【解决方案1】:

Perl on Command Line

perl -E '$match=$ARGV[1];open(Input, "&lt;", $ARGV[0]);while(&lt;Input&gt;){ ++$n if /$match/g } say $match," ",$n;' your-file your-pattern

对我来说
perl -E '$match=$ARGV[1];open(Input, "&lt;", $ARGV[0]);while(&lt;Input&gt;){ ++$n if /$match/g } say $match," ",$n;' parsing_command_line.pl my

它计算我的脚本 parsing_command_line.pl

中有多少模式 my

输出

my 3


给你
perl -E '$match=$ARGV[1];open(Input, "&lt;", $ARGV[0]);while(&lt;Input&gt;){ ++$n if /$match/g } say $match," ",$n;' test.json headers

注意
在命令提示符
一行中编写所有代码
第一个参数是您的文件
其次是你的模式
这不是一个完整的代码,因为您必须一个接一个地输入所有模式

【讨论】:

    【解决方案2】:

    您可以在变量中捕获命令的结果,例如:

    result=`cat $1 | grep header | wc -l`
    

    然后打印结果:

    echo "# headers : $b"
    

    ` 是 eval 运算符,它可以用内部命令的输出替换整个表达式。

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      相关资源
      最近更新 更多