Score:0

Regex to match lines that access a certain port and particular packets

in flag

New to Linux and the only way I can get this to work is by using the awk command unfortunately the main directions specify to not use awk.

this is what I got

#!/bin/sh
#comment Write a single RegEx to match the lines that access port 22 and only those packets
grep '\s22\s' hw0206.txt | awk {'print $4'}
#comment grep returns the whole line with matched string
#comment \s22\s regular expression to match any string containing 22 preceded or succeeded by white space

instructions

Write a single RegEx to match the lines that access port 22 and only those packets, and then return the IP address

Input file (hw0206.txt) Expected output of script
date time protocol ip-address port packet-size
2022-02-21 19:22:19 TCP 22.101.2.24 22 24
2018-22-22 02:25:12 UDP 10.221.7.22 2135 222
2200-05-22 22:26:22 UDP 22.122.6.62 2160 22
2012-22-20 15:43:22 TCP 10.121.7.222 22 122
1228-02-10 02:22:02 UDP 22.102.2.62 2089 22 
date time protocol ip-address port packet-size
2022-02-21 19:22:19 TCP 22.101.2.24 22 24
2018-22-22 02:25:12 UDP 10.221.7.22 2135 222
2200-05-22 22:26:22 UDP 22.122.6.62 2160 22
2012-22-20 15:43:22 TCP 10.121.7.222 23 122
1228-02-10 02:22:02 TCP 22.102.2.62 22 22
2100-05-25 21:26:22 UDP 22.112.63.62 2122 22
Greenonline avatar
us flag
Is this homework?
CryptoTrader avatar
in flag
no, self paced tutorial. trying to teach myself
Score:2
cn flag

With positive lookahead, you can match something that should not be part of the result:

grep -Po '(\d+\.){3}\d+(?=\s22\s)' hw0206.txt

In this case, I would prefer awk which gives a more readable solution:

awk '$5 == 22 {print $4}' hw0206.txt
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.