简体   繁体   中英

How to cd into grep output?

I have a shell script which basically searches all folders inside a location and I use grep to find the exact folder I want to target.

for dir in /root/*; do
    grep "Apples" "${dir}"/*.* || continue

While grep successfully finds my target directory, I'm stuck on how I can move the folders I want to move in my target directory. An idea I had was to cd into grep output but that's where I got stuck. Tried some Google results, none helped with my case.

Example grep output: Binary file /root/ant/containers/secret/Documents/2FD412E0/file.extension matches

I want to cd into 2FD412E0 and move two folders inside that directory.

dirname is the key to that:

cd $(dirname $(grep "...." ...))

will let you enter the directory.

As people mentioned, dirname is the right tool to strip off the file name from the path.

I would use find for such kind of task:

while read -r file
do
  target_dir=`dirname $file`
  # do something with "$target_dir"
done < <(find /root/ -type f \
  -exec grep "Apples" --files-with-matches {} \;)

Consider using find 's -maxdepth option. See the man page for find .

Well, there is actually simpler solution :) I just like to write bash scripts. You might simply use single find command like this:

find /root/ -type f -exec grep Apples {} ';' -exec ls -l {} ';'

Note the second -exec . It will be executed, if the previous -exec command exited with status 0 (success). From the man page:

-exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of ; is encountered. The string {} is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.

Replace the ls -l command with your stuff.

And if you want to execute dirname within the -exec command, you may do the following trick:

find /root/ -type f -exec grep -q Apples {} ';' \
  -exec sh -c 'cd `dirname $0`; pwd' {} ';'

Replace pwd with your stuff.

When find is not available

In the comments you write that find is not available on your system. The following solution works without find :

grep -R --files-with-matches Apples "${dir}" | while read -r file
do
  target_dir=`dirname $file`
  # do something with "$target_dir"
  echo $target_dir
done

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