5

I want to go to a directory with using filter

For example there is a file named this-is-awsome

ls | grep this-is-awsome | xargs cd

How can I go to a directory with filter?

polym
  • 10,852
  • 2
    Here is your answer cd is not an external command - it is a shell builtin function. It runs in the context of the current shell, and not, as external commands do, in a fork/exec'd context as a separate process. – Raza Jul 01 '14 at 20:51

3 Answers3

9

Salton's comment explains the problem. Here are some solutions:

cd "$(ls | grep this)"

This is probably not so good, with all the usual caveats about parsing the output of ls applying to it.

A slightly better version (assumes GNU find):

cd "$(find -maxdepth 1 -type d -name '*this*')"

Yet another (maybe even better) solution if you're using Bash:

shopt -s nullglob
cd *this*/
Joseph R.
  • 39,549
1

This works for me:

>>pwd | xclip

>>cd `xclip -o`
michabs
  • 11
  • Why do you need xclip there? – muru Sep 10 '19 at 14:09
  • Thanks @michabs. This is the only one that worked in my situation. I was using output from fzf in the ion (rust) shell. Problem is that variable expansion blocked fzf's io so xclip provides temporary storage for an output. My alias looks like

    alias z = 'export FZF_DEFAULT_COMMAND="/usr/bin/fdfind -t d -H -L -E .git -E dosdevices -E p_rsnapshot" && fzf | xclip && cd $(xclip -o)'

    – John 9631 Oct 23 '20 at 21:10
  • An alternative might be redirection to a file so that fzf | xclip && cd $(xclip -o) could be replaced by fzf > tmp__ && cd $(cat tmp__) && rm tmp__. – John 9631 Oct 23 '20 at 21:20
0

When you have one file with "this", just use

   cd *this*
Walter A
  • 736
  • This might pick up a file, which is why I have appended a / in my glob
  • This will error out if the glob fails to match, which is why I thought shopt -s nullglob was necessary.
  • – Joseph R. Jul 03 '14 at 14:46