Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare variable dynamically inside awk in bash?

Tags:

bash

sh

awk

I want to dynamically compare the value of two variable and write the answer to a file:

#!bin/bash
Timestamp2="19:16:35"

cat find_thread |awk -F'.' '{print $1}'|awk '{for (i=1; i<=NF;i++) {if ( $i == $(Timestamp2)  ) {print (i-1)}}}'>ThreadID

where find_thread file has the following content:

8361 19:16:35.493540
8361 19:16:35.493594
8360 19:16:41.242314
8360 19:16:41.242343
8278 19:16:39.179931
8278 19:16:39.179973
like image 672
fiddle Avatar asked Aug 12 '26 04:08

fiddle


1 Answers

If I understood correctly, here you go:

awk -v ts="$Timestamp2" '$2 ~ "^" ts {print $1}' find_thread > ThreadID

Explanation:

  • Put $Timestamp2 in the variable ts using the -v flag.
  • Filter by the pattern: $2 ~ "^" ts = the 2nd column (for example 19:16:35.493540) should start with ts
  • Print the 1st column of matched lines

Here's another variation of the same thing:

awk -F'[ .]' -v ts="$Timestamp2" '$2 == ts {print $1}' find_thread > ThreadID
like image 165
janos Avatar answered Aug 15 '26 01:08

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!