LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   adding constant (number) to a number in all rows (https://www.linuxquestions.org/questions/programming-9/adding-constant-number-to-a-number-in-all-rows-643639/)

skuz_ball 05-20-2008 08:39 PM

adding constant (number) to a number in all rows
 
Hi all,

I have a file which has temperatures in Kelvin in a column and would like to convert these numbers to Celsius. I think sed would be appropriate to use in this instance but having multiple lines in the file has confused me a bit. im trying to do this in a shell script. I usually use ksh to do this work but am open to any suggestions.

eg file1:

1 2 3 4
1 2 3 5
1 2 3 3
1 2 3 7

Would like to take away 3 from last column so file2 looks like this:

1 2 3 1
1 2 3 2
1 2 3 0
1 2 3 4

Any help would be greatly apprciated.

jlinkels 05-20-2008 09:46 PM

awk is your friend.

Code:

cat file1 | awk '{print $1 " " $2 " " $3 " "  $4 + 273}' > file2

That is how to convert Celsius to Kelvin. I don't understand your last conversion to take 3 away from the last column.

In sed it would be:

Code:

sed s/3\ *$/0/
jlinkels

rlhartmann 05-20-2008 09:57 PM

Here's a perl script to do it:

Quote:

#!/usr/bin/perl
while(<STDIN>) # Read from stdin
{

chomp;
@columns=split(/\s/,$_);
$columns[3]-=3;
$string=join("\t",@columns); # separate with tab
print("$string\n");
}
Give it execute permissions, and run using:
[B]./kelvin.pl < datafile >outputfile


All times are GMT -5. The time now is 11:08 AM.