【问题标题】:Make grep output more readable使 grep 输出更具可读性
【发布时间】:2014-12-24 04:38:55
【问题描述】:

我正在使用 grep 来处理带有 grep -orI "id=\"[^\"]\+\"" . | sort | uniq -d 的文件中的模式 输出如下:

./myFile.html:id="matchingR"
./myFile.html:id="other"
./myFile.html:id="cas"
./otherFile.html:id="what"
./otherFile.html:id="wheras"
./otherFile.html:id="other"
./otherFile.html:id="whatever"

什么是一种便捷的管道方式,输出如下:

./myFile.html
  id="matchingR"
  id="other"
  id="cas"
./otherFile.html
  id="what"
  id="wheras"
  id="other"
  id="whatever"

基本上按文件名对结果进行分组。

【问题讨论】:

    标签: bash command-line awk grep


    【解决方案1】:

    将输出传递给此脚本:

    #!/bin/sh
    sed 's/:/ /' | while read FILE TEXT; do
    if [ "$FILE" = "$GROUP" ]; then
        echo "  $TEXT"
    else
        GROUP="$FILE"
        echo "$FILE"
        echo "  $TEXT"
    fi
    done
    

    【讨论】:

      【解决方案2】:

      不是最漂亮的,但它确实有效。

      awk -F : -v OFS=: 'f!=$1 {f=$1; print f} f==$1 {$1=""; $0=$0; sub(/^:/, "  "); print}'
      

      如果您的任何行都不能包含冒号,那么这个更简单的版本也可以。

      awk -F : 'f!=$1 {f=$1; print f} f==$1 {$1=""; print}'
      

      这两个用冒号分割的字段 (-F :) 当第一个字段(文件名)与保存的值不同(并保存新值)并且当第一个字段与保存的值匹配时,它们会删除第一个字段并打印。它们在删除字段和打印输出的方式上有所不同。第一次尝试在匹配的行中保留冒号。第二个(和@fedorqui 的版本... f==$1 {$0=$2; print})假设没有其他冒号开始。

      【讨论】:

      • 好一个。对我来说,f==$1 {$0=$2; print} 就足够了。如果你想打印一个标签,那么print "\t",$0 就可以了。另外,这里不需要OFS。
      • @fedorqui 是的,这适用于第二个“无冒号”版本。这就是我向后工作的结果。 OFS 在第一个中是必要的,用于将行上的任何其他冒号拼凑在一起(例如,./otherFile.html:id="wheras:foo" 的一行)。
      【解决方案3】:

      这是一个简短的awk

      awk -F: '{print ($1!=f?$1 RS:""),$2;f=$1}' file
      ./myFile.html
       id="matchingR"
       id="other"
       id="cas"
      ./otherFile.html
       id="what"
       id="wheras"
       id="other"
       id="whatever"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-07
        • 2011-08-02
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        • 2012-07-02
        • 2017-04-21
        • 1970-01-01
        相关资源
        最近更新 更多