Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "cd" to a directory after "grep"? [closed]

Tags:

terminal

unix

I want to find a directory using grep then change current directory to the resulting directory. For example:

$ ls | grep 1670 |

finds me directory haib12CJS1670. I am trying to do something like below:

$ ls | grep 1670 | cd

so that my directory is set to haib12CJS1670 at a single step. Obviously my way is not working. Any suggestions? Thank you

like image 435
Supertech Avatar asked Jul 25 '12 13:07

Supertech


People also ask

How do I grep to a different directory?

If you want to find in all files of a directory, you can use grep -r /path/to/directory .

How do I grep a path in Linux?

To include all subdirectories in a search, add the -r operator to the grep command. This command prints the matches for all files in the current directory, subdirectories, and the exact path with the filename. In the example below, we also added the -w operator to show whole words, but the output form is the same.

Why does grep take so long?

If you're running grep over a very large number of files it will be slow because it needs to open them all and read through them. If you have some idea of where the file you're looking for might be try to limit the number of files that have to be searched through that way.

What does grep D do?

The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The grep is matching only lines that start with "d".


1 Answers

 cd `ls | grep 1670`

should get your cd to work (note, those are "back-ticks")

An alternative approach (some would say preferred) would be to use the $ substitution. E.g.,

 cd $(ls | grep 1670)

though I can't get this to work with the tcsh, it works fine with bash.

The first solution is shell-agnostic :)

like image 95
Levon Avatar answered Oct 06 '22 22:10

Levon