Ubuntu: How can I pipe the output of “find” to “cd”?



Question:

What should I do to search for a file in list of folders and change current directory to the directory of the file?

I tried find -name script.py | cd but it did not work (not that I was expecting it to).

Thanks for helping!


Solution:1

cd doesn't read from stdin so you can't pipe a folder name into it. But you can use "$(...)" to use the output of a command as an argument for cd:

cd "$(find -name script.py -type f -printf '%h\n' -quit)"  

-printf '%h\n' tells find to output only to folders that contains the files.

-quit tells find to quit after it found the first matching file.


Solution:2

You can use this code :

cd "$(dirname "$(find / -type f -name test | head -1)")"  

Where as you can see it will search from the top of root directory with command find / , then , it will list out regular files called test -name test , last it will change to its directory .

Note : The piping through head -1 will filter out all but the first.

dirname - strip non-directory suffix from file name

cd change directory


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »