How do i use the grep command in a different directory with out using cd

I want to search for a pattern in some files but without using cd to enter the directory they are saved in. How can i do that?

8

1 Answer

You can provide absolute path or relative path of the file. Absolute path generally starts with the root of the file system hierarchy, i.e., / and relative path starts with the name of sub-directory in the current directory that contains the files.

Absolute paths are ideal when you're currently in different hierarchy. For example, when I'm currently in $HOME/Desktop and I want to access files from c in /mnt, then I'll use absolute path, i.e., /mnt/c. On the other hand, relative paths are ideal if the folder you want to search in is in the current directory or the subdirectory of the current directory. When you use file.txt, you're actually using relative path.

If a pattern is to be searched in all the files in some directory, * can be used in shells which supports glob or alternatively, -r option of grep can be used which would search in all files in the directory recursively. For example:

grep -r pattern /absolute/path/of/the/file

Or if the symlinks are to be ignored, -R can be used

grep -R pattern /absolute/path/of/the/file

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like