-1

I executed a script that printed out some data. It looks something like this:

pi@pitwo:~/testing $ python3 scripts/test.py
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

What I'm looking for is a bash command way to count the length of the data.

I could write a script that does some counting, or even count it by hand since it's short, but I'd like to get your input on how you linux/unix veterans would do this.

2
  • 1
    Define length, you want to know the number of 1s and 0s or the number of overall characters? Will they always be 1s and 0s? Commented Dec 17, 2020 at 14:49
  • It always depends on the output format and what exactly do you count. Here it's a python array, so probably you could just print(len(my_array)) into your python program. What if an array element is "1,2"? The general solution is to have a well-defined delimiter and count the items. It could be the space or the comma or the newline etc. And if the delimiter is allowed inside fields (see csv, json, etc) it gets complicated, it's more than just serially counting fields. Commented Dec 17, 2020 at 15:04

3 Answers 3

4

Using awk:

awk -F, '{print NF}'

This will use comma as a field separator and print the total number of fields.

2

As that looks like a json array, you could just pipe it to

jq length
0

You should use wc instead of awk, why? awk is generally a larger program, always try to minimize the horsepower needed to your particular case. If the only thing you have to count are python-like lists, i.e., [a, b, c], then wc is your best bet. But for more complex tasks you might need to use awk.

In your example:

pi@pitwo:~/testing $ python3 scripts/test.py | wc -w
48

Here we use the -w flag to tell wcthat we want the word count (man wc for more).

2
  • What if the array contains whitespace? ["this is still", "a valid array"] Commented Dec 17, 2020 at 18:59
  • That's why I said for that (his) particular case, should've specified a, b, c, etc. are numbers Commented Dec 18, 2020 at 19:05

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.