0

In bash, usually you cannot send the output of tcpdump to an awk expression, as explained in this Stack Exchange question. This prints nothing:

sudo tcpdump -i en1 -n -q 'tcp[13]=18 and src port 80' | awk '{$0=$3; sub(".80$",""); print $0}'

The solution is to buffer the output with the -l flag, like this, which works as expected:

sudo tcpdump -i en1 -n -q -l 'tcp[13]=18 and src port 80' | awk '{$0=$3; sub(".80$",""); print $0}'

However, when I tried to pipe the output of the awk to a file or anywhere else, the file is created but stays empty, even if tcpdump says that it received packets.

sudo tcpdump -i en1 -n -q -l 'tcp[13]=18 and src port 80' | awk '{$0=$3; sub(".80$",""); print $0}' | tee -a file.txt

or

sudo tcpdump -i en1 -n -q -l 'tcp[13]=18 and src port 80' | awk '{$0=$3; sub(".80$",""); print $0}' | awk '{print $3}' >> file.txt

My workaround has been to output to a file, and then run the awk on the file later, exporting to another file, but this makes it impossible to read the edited file in realtime. Any ideas on why this happens?

Community
  • 1
  • 1
shardbearer
  • 365
  • 1
  • 4
  • 7
  • `awk` also buffers its output (most programs buffer output when they write to a file or pipe, because this is the default behavior of stdout). Unfortunately, it doesn't have an option like `tcpdump -l` to tell it not to buffer. – Barmar Jun 30 '13 at 08:53
  • I had simplified the code snippets to make them easier to read, and now the first one works, but my original still doesn't. Changing code snippets now. – shardbearer Jun 30 '13 at 08:57
  • The code snippets don't really matter, the solution is the same regardless of what you're doing. You just need to flush after you print. – Barmar Jun 30 '13 at 09:01

1 Answers1

4

awk has an fflush function that sends the output buffer:

sudo tcpdump -i eth0 -q -l | awk '{print $3; fflush}' | tee -a file.txt
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Only `gawk` and `BSD awk` have `fflush()`,. `mawk` has `-w interactive`. Other awks can use repeat close and append operations. – Scrutinizer Jun 30 '13 at 09:50