Ubuntu – How to use grep output as a path for cd

bashcommand linedirectorygrep

How can I pipe grep output as an argument to the cd command?

For example:

[root@xxx xxx]# pip install django | grep '/usr.*'  
Requirement already satisfied (use --upgrade to upgrade): django in   /usr/lib64/python2.7/site-packages

Here /usr/lib64/python2.7/site-packages is highlighted and I want to pass this string to cd.

Best Answer

Use Bash's command substitution $(), you also need -o with grep to only select the matched portion:

cd "$(pip install django | grep -o '/usr.*')"

Note that although you will get away in this case but you should always enclose the command substitution with double quotes so that the shell does not perform word splitting on whitespaces (by default space, tab and newline, depends on the IFS variable in case of bash).

Related Question