LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Read second line from file with awk and use as variable. (https://www.linuxquestions.org/questions/programming-9/read-second-line-from-file-with-awk-and-use-as-variable-4175438418/)

pampers 11-23-2012 06:14 AM

Read second line from file with awk and use as variable.
 
Hello.

I have a file like this:

Code:

13:36
13:38
13:39

I have to read the last 2 lines and compare both times and print how much minutes or seconds had passed from each other. I have the following awk script:

PHP Code:

{

hora1=substr($1,1,2);
minuto1=substr($1,4,2);
#segundo1=substr($2,7,2);

hora2=substr($2,1,2);
minuto2=substr($2,4,2);
#segundo2=substr($3,7,2);

tiempo1=hora1*60*60 minuto1*60;
tiempo2=hora2*60*60 minuto2*60;

diff=tiempo1-tiempo2;

printf "%s %d:%d:%d\n","La diferencia es ",diff/(60*60),diff%(60*60)/60,diff%60;



which reads a file and print results without problem, if the file were like this:

13:36 13:38
13:40 13:45
13:50 13:55

It works fine this way, but how can I make awk read the second line and print results without problem? Since the file I want to read is in the following format:

13:36
13:38
13:40
13:45


Thanks in Advanced, for any help.

pan64 11-23-2012 06:24 AM

something like this should work
Code:

awk ' NR % 2 == 0 { hora1=substr($1,1,2); minuto1=substr($1,4,2) }
      NR % 2 == 1 { hora2=substr($1,1,2); minuto2=substr($1,4,2)

tiempo1=hora1*60*60 + minuto1*60;
tiempo2=hora2*60*60 + minuto2*60;

diff=tiempo1-tiempo2;

printf "%s %d:%d:%d\n","La diferencia es ",diff/(60*60),diff%(60*60)/60,diff%60;

 } ' textfile


pampers 11-23-2012 06:45 AM

Hey cool :D it does work :D I really appreciate a lot your help.

I am extremely newbie in awk programming, so there,s a bunch of things I still need to learn and understand. Your modification does work very well :)

There,s a little inconvenience, maybe I have missed something here don,t know. Well I have a file (let's call it textfile.txt) with the following times let said:

13:30
13:35
13:50

etc, etc. When I execute your awk script like this:

bash$ awk -f myawkscript.awk < textfile.txt

The results I get back are as follow:

-13:30
0:15:0
0:15:0

How can I omit printing the first line from the textfile.txt? I just want the results from the times calculation.

Sorry if this is too newbie :) I really appreciate any help you can provide.

pan64 11-23-2012 06:57 AM

I think I made a mistake, first you need NR % 2 == 1 and in the second line NR % 2 == 0.

pampers 11-23-2012 07:50 AM

Thanks Pan64 :) I made the change, but unfortunately it keeps printing the first line on stdout. What I did was, a bash script that do a tail command that read only the last 2 lines, so this way I avoid any below line. It works this way :)

I appreciate all your help in providing a solution for my request.

Thanks :)


All times are GMT -5. The time now is 01:16 PM.