正则表达式与awk匹配
我正在用 awk 搞乱一些,而且我对 bash/awk 还很陌生,所以
当我这样做来查找以 root 身份运行的所有进程时,请耐心等待
ps aux | awk '$0 ~ /.*root*./ {print $0, $11}'
,它会按我的预期打印出所有内容,但它也会打印出底部的行包括我的用户名(不是 root)和进程 awk。这是为什么?我能做什么呢?
注意:我对打印所有具有 root 的进程的替代解决方案并不真正感兴趣。我已经可以做到了。我想了解这里发生了什么以及如何使用它。
I'm messing around a little with awk and I am still kind of new to bash/awk so bear with me
when I do this to look for all processes running as root
ps aux | awk '$0 ~ /.*root*./ {print $0, $11}'
it prints out everything as I expect, but it also prints out a line at the bottom that includes MY username (which isn't root) and the process awk. Why is that? What can I do about it?
Note: I'm not really interested in alternate solutions to print out all the processes that have root. I can already do that. I want to understand what is going on here and how I can use this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
避免打印 awk 进程的方法是这样的:
该 hack 的工作原理如下:awk 将搜索字符序列 'r' 'o' 'o' 't'。实际的 awk 进程不匹配,因为 ps 输出包含字符序列 '[' 'r' ']' 'o' 'o' 't'。
The way to avoid the awk process from being printed is this:
That hack works like this: awk will be searching for the sequence of characters 'r' 'o' 'o' 't'. The actual awk process is not matched because the ps output contains the sequence of characters '[' 'r' ']' 'o' 'o' 't'.
似乎有几个问题:一是你有 *.而不是“root”后面的.*。另一个是您正在搜索整行,而不仅仅是包含用户名的列。
$0 代表整行。 $1 代表第一列。
更接近你想要的东西会是
但你也可以这样做
There seem to be a couple of issues: One is that you have *. instead of .* after "root". The other is that you are searching the whole line and not just the column that contains the username.
$0 represents the entire line. $1 represents the first column.
Something closer to what you want would be
but you could also just do
要完全匹配您编写的第一个字段,
您还可以要求
ps
为您进行过滤To exactly match the first field you write
you can also ask
ps
to filter for you这是你想要的吗?
你有“最后一行”的原因是你的正则表达式是.root.。并且您的 ps|awk 行具有相同的字符串。所以它被选中。
也许你可以使用 grep -v "awk" 来过滤你的 awk 行。
is this what you want?
the reason that you have the "last line" is your regex was .root.. and your ps|awk line has the same string. so it is selected.
maybe you can with grep -v "awk" to filter your awk line out.
如果您需要仅匹配 root 拥有的进程(即以字符串 root 开头的记录):
请注意
/regex/
和$0 ~ /regex/
是等效的。If you need to match only process owned by root (i.e. records beginning with the string root):
Note that
/regex/
and$0 ~ /regex/
are equivalent.