简体   繁体   中英

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
  • 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. I think I can use awk somehow, but I am not so familiar with it.

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 -hr '^\s*/|\$\(\s*/|\`\s*/' /etc/rc.d/* /etc/init.d | sed -e 's/\($(\|)\)//g'

That sed regex will delete all the "$(" and ")"

OK, thanks to the help from alb3rtobr, I was able to get it:

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. I also modified the sed to trim leading whitespace.

EDIT: Changed to match pattern while not a space character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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