Using sed to extract specific log information

I have this journal from which I would like to extract information. I want to use sed to extract it.

 Nov 12 19:56:52 libra kernel: [ 1353.27355] WarningIN=em0 OUT=eth0 MAC=c8:1b:3c:fd:5D:e9:90:a9:8F:43:83:E3:15:0e SRC=222.171.89.16 DST=49.137.111.136 LEN=222 TOS=0x8C PREC=0xbF TTL=107 ID=31469 PROTO=ICMP TYPE=35 CODE=8 ID=24917 SEQ=166 19:56:52 12 Nov;Warning;em0;eth0;222.171.89.16;49.137.111.136;ICMP;; 

I am having trouble understanding my sed . If someone could fix me here, that would be great. I wanted to get the date first of all, so I wrote

 $ sed 's/\([0-9][0-9]:[0-9][0-9]:[0-9][0-9]\).*/\1/' file.log 

but my conclusion

 Nov 12 19:56:52 

I don’t understand why I’m not just getting 19:56:52

+4
source share
3 answers

Use this template:

 sed -r 's/(^.*\s)([0-9][0-9][:][0-9][0-9]:[0-9][0-9])(.*$)/\2/' 

Here is an example:

 echo "Nov 12 19:56:52 libra kernel" | sed -r 's/(^.*\s)([0-9][0-9][:][0-9][0-9]:[0-9][0-9])(.*$)/\2/' => 19:56:52 

If you just want to print the entire contents of the file using sed, you can do this using:

 sed r FILE 

If you want sed to act like grep :

 sed -n '/regexp/p' FILE # method 1 sed '/regexp/!d' FILE # method 2 

Or if you want it to act like grep -v

 sed -n '/regexp/!p' FILE # method 1, corresponds to above sed '/regexp/d' FILE # method 2, simpler syntax 

You can also find a number of sed liners here (in fact, the above grep examples were taken from the webpage linked here - except that I added FILE for each of them)

+1
source

Simply put, you are not just getting 19:56:52 because your template is not Nov 12 .

If you add .* the beginning of your template in accordance with Nov 12 , it will work as you expect. Here is the corrected command:

 $ sed 's/.*\([0-9][0-9]:[0-9][0-9]:[0-9][0-9]\).*/\1/' file.log 
+1
source
 sed -n 's/\([[:alpha:]]\{3\}[[:blank:]]\{1,\}[0-9]\{1,2\}\)\{0,1\}[[:blank:]]\{1,\}\([0-9]\{1,2\}:}[0-9]\{1,2\}:}[0-9]\{1,2\}\).*/\2/p' YourFile 

take the first hour if (in one case)

  • is after the month / day format (November 12) that launches the line
  • after a space (if any) at the beginning of a line

and print it

It is not required that the hour be somewhere else or with a different template (and do not print the line)

+1
source

Source: https://habr.com/ru/post/1493850/


All Articles