简体   繁体   English

Bash脚本将仅替换第一行

[英]Bash script that will replace only the first line

I want to extract the timestamp of the packets using tcpdump and put it into a file, in such a way that the latest timestamp replaces the first line (which either is empty or contains the the timestamp of the second-last packet). 我想使用tcpdump提取数据包的时间戳并将其放入文件中,以使最新的时间戳替换第一行(该行为空或包含倒数第二个数据包的时间戳)。 Its necessary that the file should only have a 1 line entry ie. 该文件仅应具有1行条目(即。 the timestamp of the latest packet. 最新数据包的时间戳。

This is what I did: 这是我所做的:

sudo tcpdump -i eth0 -l | cut -d . -f1 >  test.txt

cat test.txt
16:08:04
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05

But what I want is only the latest timestamp: 但是我想要的只是最新的时间戳:

cat test.txt
16:08:05

Any Ideas? 有任何想法吗?

From what I've tested, it looks like your script will run forever and you may need to see the last packet in another process, isn't it? 根据我的测试,看起来您的脚本将永远运行,您可能需要查看另一个进程中的最后一个数据包,不是吗?

$ cat test.txt

16:08:04
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05

If you only want the latest packet (ie the last line), please try 如果您只想要最新的数据包(即最后一行),请尝试

$ tail -1 test.txt

16:08:05

if you want to see the latest packet together with the rest, please try 如果您想与其他人一起查看最新的数据包,请尝试

$ tail -1 test.txt > tmp_out; cat test.txt >> tmp_out; cat tmp_out

16:08:05
16:08:04
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05
16:08:05

Using awk you can do: 使用awk,您可以执行以下操作:

sudo tcpdump -i en0 -l -c 5 2>/dev/null | awk -F'\\.' '$1~/^[012][0-9]:/{p=$1} 
   END{print p > "output"}'

cat output
08:27:51

This will get max timestamp and store it in file called output . 这将获得最大时间戳并将其存储在名为output文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM