LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Awk variables (https://www.linuxquestions.org/questions/programming-9/awk-variables-934994/)

carlr 03-17-2012 04:23 PM

Awk variables
 
Hi,

I am learning Awk and unix programming. I have a file of data, the first column in time. I have parsed the original files into multiple files each containing 1 cycle. I want to normalise the time in each file so that each file starts from time 0 s. Obviously the first cycle starts from 0 s any way.

I have many cycle files to do so i don't want to do this manualy. Eventually this will all be put in a loop so that i can do all the files with the name cycle_data_* in a given folder.

Using Awk how do I set "t_norm" to be the value of $1 of line 1 when it is processing all lines in the file in the below script?

awk -F, "{print ($1-(t_norm)) "," $2 "," $3 "," $4} Cycle_file.txt > Cycle_file_T_normalised.txt


I have also tried doing this another way, whereby I firstly create a file (file_init_time.txt) with the value which needs to be subtracted from the value $1 of each line in the file. However, i am struggling passing values between the awk commands. I have tried different ways but can't get it to work either.

awk -F, -v VAR1='${$1}' file_init_time.txt |& awk -F, '{print ($1-$VAR1) "," $2 "," $3 "," $4}' Cycle_Data_11_T.txt > Cycle_Data_T_Norm.txt


Any help would be much appreciated
I'm using Cygwin.

Carl

colucix 03-17-2012 05:04 PM

Hi Carl and welcome to LinuxQuestions! :)
Quote:

Originally Posted by carlr (Post 4629351)
Using Awk how do I set "t_norm" to be the value of $1 of line 1 when it is processing all lines in the file in the below script?

Just add a rule to be executed only for the first record, e.g.
Code:

awk -F, 'NR==1{t_norm=$1}{print ($1-(t_norm)) "," $2 "," $3 "," $4}' Cycle_file.txt
where NR is the current record number (a record in awk is a single line of input). Hope this helps.

carlr 03-17-2012 05:35 PM

I can't get this to work. There is something wrong with the syntax which i can't seem to solve.

awk -F, '{ {NR==1 t_norm=$1} {print ($1-t_norm) $2 "," $3 "," $4} }' Cycle_Data_11_T.txt > Cycle_Data_11_T_help.txt

colucix 03-17-2012 06:05 PM

Quote:

Originally Posted by carlr (Post 4629381)
I can't get this to work. There is something wrong with the syntax which i can't seem to solve.

awk -F, '{ {NR==1 t_norm=$1} {print ($1-t_norm) $2 "," $3 "," $4} }' Cycle_Data_11_T.txt > Cycle_Data_11_T_help.txt

This is not what I suggested. The expression NR == 1 should be outside the braces.

Edit: sorry, I've corrected misspelled quotes in my previous post. Please, try it now.


All times are GMT -5. The time now is 12:38 AM.