3

我在我的 python 脚本中使用了两个简短的 UNIX 命令来获取有关附近无线接入点的一些数据。

  • n°1,获取接入点的 ESSID:

"iwlist NIC scan | grep ESSID | awk '{print $1}'"

  • n°2,获取接入点的信号强度:

"iwlist NIC scan | grep level | awk '{print $3}'"

我的问题是我一个接一个地使用这两个命令,这意味着它不会生成“对称”数据。您可能会获得 6 个 ESSID 和 4 个信号强度数据。

因为第一次,脚本找到了 6 个 AP(A、B、C、D、E 和 F),而下一次只找到了 4 个 AP(A、C、E 和 F)。

我的一些问题如下:

  • 有没有办法“拆分”第一个结果,iwlist NIC scan然后将两个不同的grepawk序列应用于同一个输入?

只是为了让你至少得到一个对称的结果列表。

先感谢您 !

4

3 回答 3

10

awk使用as怎么样grep

iwlist NIC scan | awk '/ESSID/ {print $1} /level/ {print $3}'

这会同时为您提供 ESSID 和电平线。你可能想要更复杂一点,至少用它所代表的来标记线条;选项很多。从您的代码中不清楚您将如何使用输出,所以我不会尝试并猜测如何最好地呈现它(但我希望同一行上的网络 ID 和级别会是一个很好的输出——这是可行的)。

于 2012-09-23T00:33:40.040 回答
4

In general, you can accomplish this type of routing using tee and process substitution:

iwlist NIC scan | tee >( grep -i ESSID | awk '{print $1}' ) | grep -i level | awk '{print $3}'

but this is inferior in this situation for several reasons:

  1. grep is superfluous, since awk can do the filtering itself
  2. The two branches are similar enough to fold into a single awk command, as Jonathan Leffler points out.
  3. The two output streams are merged together in a nondeterministic manner, so it may be difficult or impossible to determine which level corresponds to which ESSID. Storing the output of each branch in a file and later matching them line by line helps, but then this is not much better than asgs's solution.

But the technique of passing one command's output to two different pipelines without an explicit temporary file may be useful elsewhere; consider this answer just a demonstration.

于 2012-09-23T13:09:10.807 回答
1
#!/bin/bash
iwlist <NIC> scan > tmpfile
grep -i ESSID tmpfile | awk '{print $1}'
grep -i level tmpfile | awk '{print $3}'
rm tmpfile

像这样的脚本可能会做你所期望的。

于 2012-09-23T00:14:31.207 回答