0

I have a file called test_data.txt and inside the file is the below:

20:20:20 test1
20:21:21 test2
20:21:49 test3
20:21:57 test4
20:21:57 test5
20:21:57 test6
20:22:57 test7
20:25:59 test8
20:25:59 test9
20:25:59 test10
20:25:59 test11
20:29:03 test12
20:29:04 test13
20:29:31 test14

The 1st column is what I want to search on for example. The 1st column present hours:minutes:seconds (HH:MM:SS). I would like to use variables to pull data for the entire line if the hour and minutes are met:

var1=20:20
var2=20:22
cat test_data.txt | awk '{if ($1 == "'"$var1"'" || $1 == "'"$var2"'") print $0;}'

Expected output:

20:20:20 test1
20:22:57 test7

The awk I am using clearly does not work, because I do not want to search on seconds. The below method does work, but how do I use multiple variables in the example:

var1=20:20
var2=20:22
ERE='^'$var1':[[:digit:]]+$' <test_data.txt awk '$1 ~ ENVIRON["ERE"]'

I am not sure if the above can handle multiple variables in the same command as one

Output from above command:

20:20:20 test1
1
  • ~ matching, unlike ==, doesn't have to be total, ERE supports disjunction, and an awk var is easier than an envvar: <file awk -v ere="^(20:20|20:22)" '$0~ere' Commented Nov 17, 2022 at 2:07

2 Answers 2

2

You could pass multiple HH:MM values into awk as a space-separated string, and then break that into an array in the awk BEGIN block. Then for each record of the data file, test if $1 starts with one of the HH:MM strings.

awk -v times="20:20 20:22" '
  BEGIN {n = split(times, t)}
  {for (i=1; i<=n; i++) if (index($1, t[i]) == 1) {print; break}}
' test_data.txt
0

Building on some of @glennjacman's code - you could create a hash table from the target times and use a hash lookup on the input values for efficiency:

awk -v times="20:20 20:22" '
    BEGIN {
        split(times, tmp)
        for ( i in tmp ) {
            t[tmp[i]]
        }
        FS = ":"
    }
    ($1 FS $2) in t
' test_data.txt
20:20:20 test1
20:22:57 test7

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.