简体   繁体   English

Shell脚本从单行输出中获取变量计数

[英]Shell script to get count of a variable from a single line output

How can I get the count of the @ character from the following output. 如何从以下输出中获取@字符的计数。 I had used tr command and extracted? 我用过tr命令提取了吗? I am curious to know what is the best way to do it? 我很想知道什么是最好的方法? I mean other ways of doing the same thing. 我的意思是做同一件事的其他方式。

{running_device,[test@01,test@02]},

My solution was: 我的解决方案是:

echo '{running_device,[test@01,test@02]},' | tr ',' '\n' | grep '@' | wc -l

I think it is simpler to use: 我认为使用起来更简单:

echo '{running_device,[test@01,test@02]},' | tr -cd @ | wc -c

This yields 2 for me (tested on Mac OS X 10.7.5). 这对我来说产生2(在Mac OS X 10.7.5上测试)。 The -c option to tr means 'complement' (of the set of specified characters) and -d means 'delete', so that deletes every non- @ character, and wc counts what's provided (no newline, so the line count is 0, but the character count is 2). tr-c选项表示(指定字符集的)“补码”, -d表示“删除”,以便删除每个非@字符,并且wc计数提供的内容(没有换行符,因此行数为0 ,但字符数为2)。

Nothing wrong with your approach. 您的方法没有错。 Here are a couple of other approaches: 这是其他几种方法:

echo $(echo {running_device,[test@01,test@02]}, |awk -F"@" '{print NF - 1}')

or 要么

echo $((`echo {running_device,[test@01,test@02]} | sed 's+[^@]++g' | wc -c` - 1 ))

The only concern I would have is if you are running this command in a loop (eg once for every line in a large file). 我唯一关心的是如果您正在循环运行此命令(例如,对于大文件中的每一行都运行一次)。 If that is the case, then execution time could be an issue as stringing together shell utilities incurs the overhead of launching processes which can be sloooow. 如果真是这样,那么执行时间可能会成为问题,因为将外壳程序实用程序串联在一起会产生启动过程的开销,而启动过程可能会很麻烦。 If this is the case, then I would suggest writing a pure awk version to process the entire file. 如果是这种情况,那么我建议编写一个纯awk版本来处理整个文件。

Use GNU Grep to Avoid Character Translation 使用GNU Grep避免字符翻译

Here's another way to do this that I personally find more intuitive: extract just the matching characters with grep, then count grep's output lines. 这是我个人觉得更直观的另一种方法:使用grep仅提取匹配的字符,然后计算grep的输出行。 For example: 例如:

echo '{running_device,[test@01,test@02]},'   |
     fgrep --fixed-strings --only-matching @ |
     wc -l

yields 2 as the result. 结果为2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM