Issue
I need to match and return the values below the number range 12-00 in the first line/row (UTC) of the following text file:
UTC 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 00 01 02 03 04 05 06
TMP 54 53 52 50 49 48 47 47 47 48 48 48 48 48 47 45 44 43 43 41 40 39 38 37 36
So that is, matching 12 13 14 15 16 17 18 19 20 21 22 23 00
in Line 1 and returning 47 47 47 48 48 48 48 48 47 45 44 43 43
from Line 2.
My Attempt:
cat some.text.file | head -n 3 | grep -A 1 '12.*.00' | tail -n 1
Result:
TMP 54 53 52 50 49 48 47 47 47 48 48 48 48 48 47 45 44 43 43 41 40 39 38 37 36
Expected Result:
12 13 14 15 16 17 18 19 20 21 22 23 00
47 47 47 48 48 48 48 48 47 45 44 43 43
Solution
This can be done in a single awk
:
awk 'NR == 1 {for (i=1; i<=NF; ++i) if ($i == "12") start = i; else if ($i == "00") stop = i} {for (i=start; i<=stop; ++i) printf "%s", $i (i < stop ? OFS : ORS)}' file
12 13 14 15 16 17 18 19 20 21 22 23 00
47 47 47 48 48 48 48 48 47 45 44 43 43
A more readable version:
awk 'NR == 1 {
for (i=1; i<=NF; ++i)
if ($i == "12")
start = i
else if ($i == "00")
stop = i
}
{
for (i=start; i<=stop; ++i)
printf "%s", $i (i < stop ? OFS : ORS)
}' file
Answered By - anubhava Answer Checked By - Mildred Charles (WPSolving Admin)