Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to do ls | grep something and cd to the one thing that is listed. I tried with | and searched, but nothing found. Is it using xargs?

share|improve this question
Why was this down voted? – Soviero Jul 25 '12 at 6:28
You don't provide any kind of example or input; please tell us what exactly you wish to achieve. – adaptr Jul 25 '12 at 9:26
xargs won't work, as it is a separate process, but the current working directory is specific to each process. So you have to use a shell builtin command, not some binary you start as a separate process. – MvG Jul 26 '12 at 21:51

You can do

$ cd $( ls | grep foo )

but that will only work if the result is relative to where you are currently; for anything more you'll want find (it will print paths) and a very specific grep pattern.

share|improve this answer

If the pattern you want to match can be expressed as a glob, and you know that there will only be one match, you can let your shell do the matching:

$ cd *foo*

Otherwise the easiest option is to command substitution to provide the parameter to cd:

$ cd $(ls | grep '*foo*' | head -n1)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.