Skip to Content

doing arithmetics with columns

mborn's picture

Assalamo Alikum, How are you all?

I use "seq" to generate a sequence of numbers and direct them to a file. Now if I have two files (each with different sequence of numbers) am I able to do simple arithmetics with them? That is, can I add the columns in the first file to the one in the second file? Can I subtract, multipy, and divide the first by the second?

Also, is it possible to do these basic arithmetic operations on just one file? That is, to multiply (divide, add, and subtract) the column of numbers with a constant?

Thanks a lot;

Max

YoussefAssad's picture

Pretty simple with shell scripting.

man bash

--

mborn's picture

Scirpting

Thank you, but now since you mentioned it, How may I learn bash scripting? Do you know a good place to start from? A good book? a good introductory report or assay?

Thank you for ur time,

PS. That was the fastest reply I ever got. M B

Alaa's picture

the linux documentation

Alaa


"context is over-rated. who are you anyway?"

Alaa's picture

yes you can do that with

yes you can do that with awk

$ man awk
$ info awk

Alaa


"context is over-rated. who are you anyway?"

YoussefAssad's picture

bash

Doesn't even need awk, bash can do quite a bit...

--

Alaa's picture

I meant awk for doing

I meant awk for doing operations on two columns tab3an.

Alaa


"context is over-rated. who are you anyway?"

ikhnaton2's picture

There're many variant methods

There're many variant methods to do the required operation. Here under are ideas came to me.

If you have 2 files (file1, file2), each of them has one column and u want to multiply each element here with each element there, just use nested for loop like follows:

 for i in `cat file1`
 do
   for j in `cat file2`
   do
     echo $i "*" $j "=" $(($i*$j))
   done
 done

Of course u can use any operation other than multiplication.

To multiply by constant, just use YoussefAssad code.

But, if each file contain multiple column, use awk (or cut) as follows:

 for i in `cat file1 | awk '{print $1}'`
 do
   for j in `cat file2 | awk '{print $1}'`
   do
     echo $i "*" $j "=" $(($i*$j))
   done
 done

piping to "awk '{print $x}'" extract the column x.

U could also piping to cut -f x -d y which will do the same where x is the column and y is a string (between doublequote) that sets the delimiter.

Otherwise, if file1 and file2 contain one column and u want to multiply each row in file1 to the corresponding column only in file2, use the following code:

 paste file1 file2 | awk '{print $1" * "$2" = "$1*$2}'

Wish this example codes make things more clear to u.


mborn's picture

Thanks for these tips mt

Thanks for these tips mt freind, I will try them right away.

Thank you for ur time,

M B

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.


Dr. Radut | forum