0

I have an access log file with different port numbers in column 2. I want to list all traffic which went through even numbered ports. How can I do it?

1
  • 3
    Add an example chunk and your desired output from that.
    – heemayl
    Oct 31 '16 at 7:42
3

No expert in awk, but here's a simple example of using the modulus operator:

echo "foo bar 2
bar foo 3
foobar barfoo 4" | awk '($3 %2 == 0)'
foo bar 2
foobar barfoo 4

Only the lines where $3 is even is printed.

1

if your log file is like below:

cat logfile

192.168.1.102 81 [15/Aug/2016:10:52:32 +0530] "some message"
192.168.1.101 8888 [15/Aug/2016:10:52:32 +0530] "some message"
192.168.1.103 80 [15/Aug/2016:10:53:33 +0530] "some message"
192.168.1.102 2323 [15/Aug/2016:10:54:32 +0530] "some message"

then you can print complete line of log message which have even port number using below command:

while read line; do if [ $((`echo "$line"|awk '{ print $2 }'` % 2)) -eq 0 ]; then echo "$line"; fi ; done < "logfile"

which will produce output like:

while read line; do if [ $((`echo "$line"|awk '{ print $2 }'` % 2)) -eq 0 ]; then echo "$line"; fi ; done < "logfile"
192.168.1.101 8888 [15/Aug/2016:10:52:32 +0530] "some message"
192.168.1.103 80 [15/Aug/2016:10:53:33 +0530] "some message"

OR

if you want to print only port no then you can do like:

for i in `cat logfile | awk '{ print $2 }'`; do if [ $(($i % 2)) -eq 0 ]; then echo "Port number: $i"; fi ; done

Port number: 8888
Port number: 80

Note: i am assuming you don't have blank line in your log file.

1
  • 3
    this look very complicated, why not use awk '$2 % 2 == 0 ' logfile ?
    – Archemar
    Oct 31 '16 at 10:05
0

Depending on the file format that you use (delimiter space, comma, pipe, etc):

cat <filename> | awk -F"<delimiter>" '{if ($<column number> %2 == 0){print $0}}'

Sample file that I have created as below :

/ : server1> cat test1
a 2
b 1
c 5
d 6
e 9
f 8

I will perform query as below to get desired output :

/ : server1> cat test1 | awk -F" " '{if ($2 %2 == 0){print $0}}'
a 2
d 6
f 8
2
  • You dont really need the if and print, a simple '($2 %2 == 0)' will suffice. Oct 31 '16 at 10:11
  • Hi @maulinglawns, noted on this, reason i used print method is in case if one wants to print only certain column, they can print it this way. Example, if they want to print column 1 and column 3 upon hitting even number port, they can use like this to display what they want : {print $1","$3}
    – einstein6
    Oct 31 '16 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.