0

I have a text file which contain numbers

numbers.txt

a,1
b,2
c,2000
d,1001
e,4
f,3

I am trying to get all the values from column 2 and do a line count and print the total

awk -F, '{if($2 >= 0 && $2 <= 999) print "%10s" "%40s" , "Total", $2}' "numbers.txt" | sort -n | wc -l

It gives me only the output of this

4

if I use printf

awk -F, '{if($2 >= 0 && $2 <= 999) printf "%10s" "%40s" , "Total", $2}' "numbers.txt" | sort -n | wc -l

It gives me only the output of this

1

whereas I need the output to be like this

total 4
2
  • I think you might want to use printf instead of print. Commented Nov 5, 2013 at 9:02
  • if I use printf the output will become 1. Commented Nov 5, 2013 at 9:03

1 Answer 1

3

If you want to show all lines having the 2nd field in the [0,999] range and finally show how many of these columns are, then this can make it. No need to sort -n and wc -l, awk itself can do it:

$ awk -F, '($2 >= 0 && $2 <= 999) {printf "%10s %40s\n" , "Total", $2; i++} END{print "total: "i}' file
     Total                                        1
     Total                                        2
     Total                                        4
     Total                                        3
total: 4

And if you just want the sum:

$ awk -F, '($2 >= 0 && $2 <= 999) i++} END{print "total: "i}' file
total: 4

Why was your command not working?

With print:

$ awk -F, '{if($2 >= 0 && $2 <= 999) print "%10s" "%40s" , "Total", $2}' a | sort -n
%10s%40s Total 1
%10s%40s Total 2
%10s%40s Total 3
%10s%40s Total 4

The number of lines was ok, although the format was not: to use %10s you need to use printf instead.

With printf:

$ awk -F, '{if($2 >= 0 && $2 <= 999) printf "%10s" "%40s" , "Total", $2}' a
     Total                                       1     Total                                       2     Total                                       4     Total                                       3

As per using printf without printing new lines, all output was in the same line. You just needed to add \n at the end of each printf:

$ awk -F, '{if($2 >= 0 && $2 <= 999) printf "%10s %40s\n", "Total", $2}' file
     Total                                        1
     Total                                        2
     Total                                        4
     Total                                        3
Sign up to request clarification or add additional context in comments.

2 Comments

I only want print the total of those numbers that are between 0 to 999
@user2211678 I updated explaining why your code was not working properly. You were pretty close, just a matter of printing new lines.

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.