0

How can I get the count of the @ character from the following output. I had used tr command and extracted? 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

3 Answers 3

2

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). 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).

Sign up to request clarification or add additional context in comments.

Comments

1

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 (e.g. 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.

1 Comment

thanks for both the approch both of them worked like charm, thanks for pointing out different alternative solutions
1

Use GNU Grep to Avoid Character Translation

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. For example:

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

yields 2 as the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.