write a script to parse some tcpdump output

i am trying to write a script to parse some tcpdump output, in each line of the tcpdump output, I know for sure there are 3 keywords exist:

User{different usernamehere}

NAS_ipaddr{different ip here}

Calling_station{ip or dns name here}

But the positions for these 3 keywords in the line are somehow random, I can not expect where the keyword will appear.

for example, it can be

10:00 1.2.3.4 4.5.6.7 User{test} bla NAS_ipaddr{1.2.3.6} blaba Calling_station{2.2.2.2} blablalba
10:06 blabla NAS_ipaddr{2.2.3.6} blaba Calling_station{2.2.2.2} blablalba User{test} bla
10:08 User{test} NAS_ipaddr{2.2.3.6} blabla Calling_station{a.b.c.d}

You will notice there is no fixed format for each line, and between the keywords there may or maynot have some other random words.

So is it possible read all the cotent, and extract only User{}, NAS_ipaddr{} and Calling_station{i } , then rearrange the output, put user first, nas_ipaddress second and calling_station third?

You should show some effort to solve your problem.
Anyway you can start from here:

awk '{for(i=1;i<=NF;i++){if($i~"User"){a=$i}if($i~"NAS_ip"){b=$i}if($i~"Calling_station"){c=$i}}print a,b,c}' logfile

thanks a lot!

Never thought about this way. Digging more awk guides now :slight_smile:

Sorry, while I am still looking at different awk articles, can someone tell me why my script does not work on this simple line?

16:19:34.898709 1.1.1.1 > 2.2.2.2.1645: rad-access-req 83 [id 94] Attr[ User{test} Pass NAS_port{66} NAS_port_type{Virtual} Calling_station{20.2.2.2}.2.2.2
} NAS_ipaddr{6.1.1.1} ]

And here is my script

awk '{
	for (i=1; i<=NF; i++) 
	
	if($i~/User/) { 
	a=$i 
	}

	if($i~/Calling_station/) { 
	b=$i 
        }

	{print a, b}
  }' test

I run the script but only get the "User{test}" as a result, why the calling_station does not show up in the result? Thanks!

You forgot to enclose the commands of the for loop within braces:

awk '{
  for (i=1; i<=NF; i++) {
    if($i~/User/) {
      a=$i
    }
    if($i~/Calling_station/) {
      b=$i
    }
  }
  {print a, b}
}' test

Regards