Home > Software engineering >  Print two results from awk match() functions in one line
Print two results from awk match() functions in one line

Time:08-11

There are two awk match() functions:

awk 'match($0,/[0-9] \.[0-9] \.[0-9] \.[0-9] /){print substr($0,RSTART,RLENGTH)}'

and

awk 'match($0,/2022:[0-9]{2}:[0-9]{2}:[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'

Both of them print required results independently, one matches IP address, second matches date and time.

How to combine these two functions, so their results are printed within one line?

CodePudding user response:

You can just grab IP address and store it in a variable. Later while printing date print ip and matched date together:

awk '
match($0, /[0-9] (\.[0-9]){3}/) {
      ip = substr($0,RSTART,RLENGTH)
}
match($0, /2022(:[0-9]{2}){3}/) {
      print ip, substr($0,RSTART,RLENGTH)
}
' file

CodePudding user response:

To avoid adding trailing newline you might use printf, consider following simple example, let say you have file.txt as follows

1A2B3
4C5D6
7E8F9

and have developed one command to print first digit and one command to print first uppercase letter as follows

awk 'match($0,/[0-9]/){print substr($0,RSTART,RLENGTH)}' file.txt
awk 'match($0,/[A-Z]/){print substr($0,RSTART,RLENGTH)}' file.txt

and want to print first digit space first letter in one line, then you can alter these to single command as follows

awk 'match($0,/[0-9]/){printf "%s ", substr($0,RSTART,RLENGTH)}match($0,/[A-Z]/){print substr($0,RSTART,RLENGTH)}' file.txt

which gives output

1 A
4 C
7 E

(tested in gawk 4.2.1)

  • Related