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
If you want to find in all files of a directory, you can use grep -r /path/to/directory .
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.
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.
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".
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With