2017-03-25 55 views
0

您好,我正在寻找解决此问题的方法。我有一个输出,我使用uniq -c排序。代码看起来像这样find $DIR -type f | file -b $files | sort -n | uniq -c | sort -nr有人能告诉我用什么方式可以访问前缀中数字的值吗? 我的输出是什么样子:搜索和计数匹配行

21 ASCII text 
    19 C source, ASCII text 
    16 ASCII text 
    10 ASCII text, with very long lines 
    9 HTML document, UTF-8 Unicode text, with 
    2 HTML document, ASCII text, with very lon 
    1 C source, UTF-8 Unicode text 

Exprected输出:

ASCII text         : 21 
    C source, ASCII text      : 19 
    ASCII text         : 16 
    ASCII text, with very long lines   : 10 
    HTML document, UTF-8 Unicode text, with : 9 
    HTML document, ASCII text, with very lon : 2 
    C source, UTF-8 Unicode text    : 1 

我怎样才能在文件类型前值保存到一个变量?

+1

请发布示例数据和预期输出。 –

+0

*将文件类型之前的值保存到变量中* - 您的变量在哪里? – RomanPerekhrest

回答

0

awk来救援!

... | awk '{k=$1;     # save counts   
      sub(/[^ ]+ /,"",$0); # remove the counts 
      $1=$1;     # normalize spaces 
      print $0 "\t:",k}' | # print in new order 
     column -ts$'\t'    # align tabs 

将打印

ASCII text        : 21 
C source, ASCII text      : 19 
ASCII text        : 16 
ASCII text, with very long lines   : 10 
HTML document, UTF-8 Unicode text, with : 9 
HTML document, ASCII text, with very lon : 2 
C source, UTF-8 Unicode text    : 1 

PS。你的sort -n似乎不合适,file将返回文本,你不想在这里进行数字排序。

+0

有没有办法在awk中调用bash函数? – Adam

+0

你可以在'awk'中调用bash命令,但是取决于你想达到的目的,可能不是一个好主意。 – karakfa

0

将您的管道与Bash循环结合使用,您可以在零件上运行命令并将变量分配给零件。

考虑:

$ echo "$out" 
21 ASCII text 
19 C source, ASCII text 
16 ASCII text 
10 ASCII text, with very long lines 
9 HTML document, UTF-8 Unicode text, with 
2 HTML document, ASCII text, with very lon 
1 C source, UTF-8 Unicode text 

您可以使用sed分配一个分隔符(在这种情况下,我会用:),然后读管道:

while IFS=: read -r fcnt ftype; do 
    printf "\t%-41s : %s\n" "$ftype" "$fcnt" 
done < <(echo "$out" | sed -e 's/^\([ [:digit:]]*\)\(.*\)/\1:\2/') 
    ASCII text        : 21 
    C source, ASCII text      : 19 
    ASCII text        : 16 
    ASCII text, with very long lines   : 10 
    HTML document, UTF-8 Unicode text, with : 9 
    HTML document, ASCII text, with very lon : 2 
    C source, UTF-8 Unicode text    : 1 

然后,只需更换echo "$out"部分与你的管道。

如果需要考虑效率,也可以使用相同类型的Bash正则表达式,而不要调用sed