Home > Mobile >  How to match pattern after first 32 letters using the grep?
How to match pattern after first 32 letters using the grep?

Time:12-23

I was trying to do filter lines with pattern 04:26. I just tried the command cat file1.txt | grep -E '04:26' I expect to filter the lines which contains 04:26 after timestamps. But instead I got the second line also.

file1.txt
    2022-12-23T04:26:47.748412 00:00 raspberrypi dnsmasq-dhcp[698]: DHCPREQUEST(eth0) 192.168.42.17 04:c8:07:23:04:26 
    2022-12-23T04:26:47.749307 00:00 raspberrypi dnsmasq-dhcp[698]: DHCPACK(eth0) 192.168.42.17 04:c8:07:23:34:13

How to mask first 32 letters of timestamps from matching?

CodePudding user response:

You may use this grep:

grep -E '^.{32}.*04:26' file

2022-12-23T04:26:47.748412 00:00 raspberrypi dnsmasq-dhcp[698]: DHCPREQUEST(eth0) 192.168.42.17 04:c8:07:23:04:26

Breakdown:

  • ^: Start
  • .{32}: Match first 32 characters
  • .*: Match 0 or more of any characters
  • 04:26: Match 04:26

Alternatively you can use this grep as well:

grep ' .*04:26' file

Considering the fact that you want to ignore timestamp text that is before first space in each line.


An awk solution:

awk '$NF ~ /04:26/' file

CodePudding user response:

With your shown samples please try following awk code. Simple explanation would be, setting field separator to 32 characters from starting of line, then in main program checking if 2nd field is matching everything till : followed by 04:26 if this condition matches then print that line.

awk -F'^.{32}' '$2~/^.*:04:26/'  Input_file

CodePudding user response:

How to mask first 32 letters

You might use cut to get 33th and following character in each line, let file1.txt content be

2022-12-23T04:26:47.748412 00:00 raspberrypi dnsmasq-dhcp[698]: DHCPREQUEST(eth0) 192.168.42.17 04:c8:07:23:04:26 
2022-12-23T04:26:47.749307 00:00 raspberrypi dnsmasq-dhcp[698]: DHCPACK(eth0) 192.168.42.17 04:c8:07:23:34:13

then

cut --characters=33- file.txt

gives output

 raspberrypi dnsmasq-dhcp[698]: DHCPREQUEST(eth0) 192.168.42.17 04:c8:07:23:04:26 
 raspberrypi dnsmasq-dhcp[698]: DHCPACK(eth0) 192.168.42.17 04:c8:07:23:34:13

which could then by fused with your code as follows

cut --characters=33- file.txt | grep -E '04:26'

that result in output output

 raspberrypi dnsmasq-dhcp[698]: DHCPREQUEST(eth0) 192.168.42.17 04:c8:07:23:04:26

Explanation: --characters= is used to select certain characters from each line, 33- means 33th character and following.

(tested in GNU grep 3.4)

  • Related