Unix regex to add content to file

I have content in file

like

asdfb ... 1
adfsdf ... 2
sdfdf ..   3

      

I want to write a unix command that should be able to add 1 + 2 + 3 and give the result as 6

From what I know grep and awk will be handy, any pointers will help.

+1


a source to share


4 answers


I believe the following is what you are looking for. It sums the last field in each record for the data that is read from stdin.

awk '{ sum += $NF } END { print sum }' < file.txt

      



Some notes:

  • With awk, you don't need to declare variables, they are inherited by assigning values ​​to them.
  • Variable NF

    is the number of fields in the current record. By adding it with $, we treat its value as a variable. At least that's how it works :)
  • The block END { }

    is executed only after all records have been processed by other blocks.
+4


a source


An awk

script is all you need to do this since it has objects grep

built in as part of the language.

Let's say your actual file consists of:

asdfb zz 1
adfsdf yyy 2
sdfdf xx   3

      

and you want to sum the third column. You can use:



echo 'asdfb zz 1
adfsdf yyy 2
sdfdf xx   3' | awk '
    BEGIN {s=0;}
          {s = s + $3;}
    END   {print s;}'

      

The BEGIN clause runs before any lines are processed, the END clause after all lines are processed.

A different suggestion happens for each line, but you can add additional suggestions to change the behavior based on all things ( grep

-py things).

+1


a source


This may not be exactly what you are looking for, but I wrote a quick Ruby script to accomplish your goal:

#!/usr/bin/env ruby

total = 0
while gets
    total += $1.to_i if $_ =~ /([0-9]+)$/
end
puts total

      

0


a source


Here's one in Perl.

$ cat foo.txt
asdfb ... 1
adfsdf ... 2
sdfdf ..   3

$ perl -a -n -E '$total += $F[2]; END { say $total }' foo
6

      

golf version :

perl -anE'END{say$n}$n+=$F[2]' foo
6

      

0


a source







All Articles