LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to round values in a column in a file (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-round-values-in-a-column-in-a-file-4175512588/)

santosh0782 07-29-2014 04:36 AM

How to round values in a column in a file
 
Hi,

I have a file test.txt.

cat test.txt
2014-07-25 00:00|739899.65|
2014-07-25 00:15|571028.09|
2014-07-25 00:30|64298.41|
2014-07-25 00:45|38963.27|
2014-07-25 01:00|166980.95|
2014-07-25 01:15|54133.68|
2014-07-25 01:30|610695.42|
2014-07-25 01:45|60568.26|
2014-07-25 02:00|122777.71|


how to round the numbers in 2nd column?

eklavya 07-29-2014 05:04 AM

Run the command
Code:

awk 'BEGIN{OFS=FS="|"}{$2=sprintf("%3.0f",$2)}1' test.txt

santosh0782 07-29-2014 05:25 AM

Quote:

Originally Posted by eklavya (Post 5211242)
Run the command
Code:

awk 'BEGIN{OFS=FS="|"}{$2=sprintf("%3.0f",$2)}1' test.txt

Thanks a lot :-), its working fine :-)

santosh0782 07-29-2014 06:45 AM

Quote:

Originally Posted by eklavya (Post 5211242)
Run the command
Code:

awk 'BEGIN{OFS=FS="|"}{$2=sprintf("%3.0f",$2)}1' test.txt

Hello Sir,

could you please explain the parameters in above command, so that i'll keep in mind for future refrence.

$2 is the second column, actually i didn't get this part {$2=sprintf("%3.0f",$2)}1

pan64 07-29-2014 07:56 AM

{ } is a block

sprintf("%3.0f",$2)
means you format the value of $2 as float, 3 digits and 0 decimals => that means rounded).
$2 = sprintf... means $2 is set to rounded $2.

1 is a tricky line. It is a condition and always true, therefore the block belongs to this condition will be executed always. There is no block defined, it means the default will be used which simply prints the line. (it should have been written as 1 { print }).
for detailed explanation please read the man page of awk.... or ask

eklavya 07-29-2014 07:58 AM

OFS is output field separator and FS is input field separator. Both are the Awk Built-in Variables. They define that the columns are separated with pipe (|).
$2 is second column. We need to modify this.
"sprintf()" is a string function. It acts in exactly the same way as "printf()", except that "sprintf()" assigns its output to a variable, not standard output.

You need to understand/learn awk to know how it works. Here is very small and good tutorial about awk which tells us about 8 in-built variables of the language. Take a look.
http://www.thegeekstuff.com/2010/01/...-filename-fnr/


All times are GMT -5. The time now is 06:31 PM.