How I can make AWK for all match in multiple lines

Viewed 66

Hi I have issue with AWK I need parse some text and I don't know how I can parse recursively.

I have this:

awk '/^tags: /{p=$2} /^[0-9]* /{v=$2} /^$/{print ""p" "v""}'

but that parse only first compliance, I need all match.

input (sensorId can be more than 2):

name: temperature
tags: sensorId=1
time                last   value
----                ----   -----
1593531518973361030 40.125 40.125

name: temperature
tags: sensorId=2
time                last   value
----                ----   -----
1593531338178622316 -0.062 -0.062

I'd like output:

1 40.125
2 -0.062

or

sensorId=1 40.125
sensorId=2 -0.062

I use

4 Answers

The problem is that you only print when there's a blank line. There's no blank line after the last occurrence, just the end of the file. You can match that with END.

awk '/^tags: /{p=$2} /^[0-9]* /{v=$2} /^$/{print p, v} END {print p, v}'

Another option is to print both values immediately when you match the second line.

awk '/^tags: /{p=$2} /^[0-9]* /{print p, $2}'

Like this:

awk '
    /sensorId=/{printf "%s ", $2}  # print $2 without newline if match /sensorId/
    length($1) > 10 {print $2}     # if length > 10, print $2
' file

I assume $1: 1593531518973361030 is at least 10 chars long. Adapt the min length if needed.

Output

sensorId=1 40.125
sensorId=2 -0.062

Could you please try following, written with shown samples.

awk '
/^tags/{
  found=1
  val=$NF
  next
}
found && /^[0-9]+/{
  print val,$2
  val=found=""
}
' Input_file

Explanation:

Checking if a line starting with tags then setting found to 1 then creating val and setting it to current line's last field value. Using next function to skip all further statements from here.

Then checking condition if found is SET and line starts with 19 digits then print value of val and 2nd field here. Nulify val here.

As your data looks well structured, this could work:

$ awk -v RS="" '{print $4,$NF}' file

Output:

sensorId=1 40.125
sensorId=2 -0.062

Edit: Tested with gawk 5.0.0, 2 different gawk 4.2.1's, gawk 4.1.4, gawk 4.0.2, mawk 1.9.9.6, mawk 1.3.3, awk version 20121220 and Busybox awk.

Related