Mjones8323
Mjones8323

Reputation: 109

AWK : Conditionally grab text in a file

I need to find a value in a file that has an id (say valueID1) and is less than a certain value. From that, I need to find the first value that is associated with valueID1 but has a different value id and is on a different line (say valueID2)

Say I wanted to find an id in the file called "birthday", such as birthday = xx/xx/xxxx I'd want to find the first birthday below a specific date (I'd have to use $3 to grab the actual numeric value) Then, I would want to grab the value of the second id that is near the first, so "name" as in "name = Greg." I'd want to output 'Greg' there. I only want the first result, not all of the results less than the first specified value.

Any thoughts on how to do this? This is all I've been able to do, and it doesn't work at all.

{
 if((/valueID1/ $3) < 0.1) print /valueID2/ $3; else
       /valueID2/
}

Upvotes: 0

Views: 129

Answers (1)

Hai Vu
Hai Vu

Reputation: 40688

Here are what I understand from your description, your data might look something like this:

Birthday = 2011
Name = Anna
Birthday = 1987
Name = George

In this case, you want to print out "George" because his birthday is less than 1999. If these assumptions are correct, here is how I solve it:

awk '$1=="Birthday"{birthday = $3} $1=="Name" && birthday<1999 {print $3}' birthday.txt

Discussion

  • I assume your data file is called birthday.txt
  • The first part $1=="Birthday"{birthday = $3} saves the birthday field into the variable birthday
  • Next, if the line contains "Name" we check the birthday which we saved and print

Update

If the year is always the last field, the the following would work. If it is still not working, please supply input data and expected output. It is hard to give accurate result when I don't fully understand the problem. Good luck.

awk '/BirthdayYear/{birthday=$NF} $1=="Name" && birthday<1999 {print $3}' birthday.txt

Upvotes: 1

Related Questions