Sum a column of numbers:
For the computation part of your project you may need to sum up a column of
numbers (getting that column is coming up in a minute). While programs such
as gawk can be used
for the task (a
sample program
can be found here.), it is possible to do in the shell. For example if the file
column has a column of numbers (1-4) to add one per line:
$ cat column
1
2
3
4
$ sum=$(cat column | tr \\n +)0
$ echo $sum
1+2+3+4+0
$ sum=$[sum]
$ echo $sum
10
The tr command converts the lines into plus symbols. A trailing
zero is added to make the equation syntatically correct. Then math mode is
used to compute the sum.
Getting a column of numbers
:
The cut command can be used to separate a column from a file.
It has two basic parameters of interest: the -d delimiter and the -f field
list. For example if we have a file:
$ cat data
First:Last:Middle
Clayton:University:College
and we only wanted the last names:
$ cut -d: -f2 data
Last
University
The cut command can give us that information. You can pick out multiple
fields if you like by giving a comma separated list.
- One last redirection operator. We've seen:
- Input: <
- Output: >
- Append: >>
- Pipe: |
The last is called a Here File where the file exists (or is created)
right in the script. The symbol is <<. For example:
$ Xdialog --textbox - 0 0 <<EOF
This file will be shown in the text box.
The great thing about it is that you don't have to create a separate file.
Also you can print variables and compute in it: $PWD and $[5+3] for example.
EOF
<