3

I'm struggling with a slight variation on: How to calculate by taking first field and How to round floating point numbers in shell?

I have a file that looks like (space between columns):

1533 C_P.doc 691 C_M.doc 905 G_S.doc 945 J_Z.doc 1549 J_M.doc 1701 L_B.doc 

I want to take the column of numbers and divide each number by 65 (but round up), and add a new column (ideally to left) with these numbers included. i.e.

24 1533 C_P.doc 11 691 C_M.doc 14 905 G_S.doc 15 945 J_Z.doc 24 1549 J_M.doc 27 1701 L_B.doc 

I would like this in a bash script. Is it possible? If necessary, the middle column can be removed if that makes it easier.

[Ubuntu 14.04]

0

3 Answers 3

2

Through awk and keeping middle column:

awk '{printf("%.f ", ($1/65)+0.5)}1' infile > outfile 24 1533 C_P.doc 11 691 C_M.doc 14 905 G_S.doc 15 945 J_Z.doc 24 1549 J_M.doc 27 1701 L_B.doc 

Through awk and without middle column:

awk '{printf("%.f", ($1/65)+0.5); $1=""}1' infile > outfile 24 C_P.doc 11 C_M.doc 14 G_S.doc 15 J_Z.doc 24 J_M.doc 27 L_B.doc 

Note that +0.5 is used as substitute for the ceil() function and it rounds up to the next number. And 1 on the end actives the default print.

1

You can use perl:

$ perl -MPOSIX=ceil -anle '$F[0] = ceil($F[0]/65);print "@F"' file 24 C_P.doc 11 C_M.doc 14 G_S.doc 15 J_Z.doc 24 J_M.doc 27 L_B.doc 
0

If you don't mind using python in shell and assuming that a.txt is your file:

[sreeraj@server ~]$ cat a.txt 1533 C_P.doc 691 C_M.doc 905 G_S.doc 945 J_Z.doc 1549 J_M.doc 1701 L_B.doc [sreeraj@server ~]$ for i in $(awk -v c=65 '{ print $1/c }' a.txt) ; do python -c 'print int(round('$i',0))' ; done >> b.txt [sreeraj@server ~]$ paste b.txt a.txt > c.txt [sreeraj@server ~]$ cat c.txt 24 1533 C_P.doc 11 691 C_M.doc 14 905 G_S.doc 15 945 J_Z.doc 24 1549 J_M.doc 26 1701 L_B.doc [sreeraj@server ~]$ 

This will create the file c.txt with the desired output.

How it works:

It uses awk to divide the values in the 1st column of a.txt by 65 and then use python's in-built function round() to round the decimals. Then we create a file c.txt with the output from the 'for' loop and use paste to combine the c.txt and a.txt

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.