简体   繁体   English

如何从grep结果中提取文件名?

[英]How can I extract a file name from a grep result?

I am trying to get a list of all programs executed on system startup. 我正在尝试获取系统启动时执行的所有程序的列表。

My game plan is as follows: 我的游戏计划如下:

  • grep -r the /etc/init.d and /etc/rc.d/* directories grep -r /etc/init.d/etc/rc.d/*目录
  • Search for any line that explicitly starts with "/" 搜索任何以“ /”开头的行
  • Include execution from backticks and $() 包括反引号和$()的执行
  • Assume execution is performed by specifying full path and ignore relative path execution (ie ./... ) 假定通过指定完整路径执行执行,而忽略相对路径执行(即。/ ./...

To that end, I used the following: 为此,我使用了以下内容:

egrep -r '^\s*/|\$\(\s*/|\`\s*/' /etc/rc.d/* /etc/init.d

Since it's searching files in the directories, the results list the file it was found in and the full line. 由于它是在目录中搜索文件,因此结果将列出在其中找到的文件以及整行。 I would like to now pipe the results into something to get just the file name and the pipe that into sort|uniq to get a simplified list. 现在,我想将结果通过管道传递给某种文件,以获取文件名,通过管道将管道传递给sort|uniq以获取简化列表。 I think I can use awk somehow, but I am not so familiar with it. 我想我可以以某种方式使用awk,但是我对此并不熟悉。

Example Result: 结果示例:

/etc/init.d/foo:             foo=$(/bin/echo hello)
/etc/init.d/bar:             bar=$(/bin/echo world)
/etc/rc.d/init.d/foobar:     /bin/false

Desired Output: 所需输出:

/bin/echo
/bin/false

If you add -h option to egrep, filename will not be shown. 如果在egrep中添加-h选项,则不会显示文件名。

egrep -hr '^\s*/|\$\(\s*/|\`\s*/' /etc/rc.d/* /etc/init.d | sed -e 's/\($(\|)\)//g'

That sed regex will delete all the "$(" and ")" sed regex将删除所有的“ $(”和“)”

OK, thanks to the help from alb3rtobr, I was able to get it: 好的,感谢alb3rtobr的帮助,我能够得到它:

egrep -hor '(^\s*/|\$\(\s*/|\`\s*/)[^ ]*' /etc/rc.d/* /etc/init.d | sed -e 's/\($(\|)\|^\s*\)//g' | sort | uniq  

I modified the egrep to continue matching until encountering a space and then added the -o option to return only the matched pattern. 我修改了egrep以继续匹配,直到遇到空格为止,然后添加了-o选项以仅返回匹配的模式。 I also modified the sed to trim leading whitespace. 我还修改了sed以修剪前导空白。

EDIT: Changed to match pattern while not a space character 编辑:更改为匹配模式,而不是空格字符

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

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