How to change directory into the output of grep

0

I'm working in PowerShell right now, and wanting to know how to cd into a directory without typing out the entire length of the directory name.

Let's say I have a really long directory name, abcdefghijklmnop, and I'm too lazy to type cd abcdefghijklmnop when I want to go to that folder. How could I shorten this up? I can list a single directory with grep, ls | grep abc, so I was thinking of using this same logic to apply to cd, essentially changing directory into the output of the grep command, assuming there is only 1 output.

cd | grep abc

Obviously that doesn't work, but is there a way to do this, or maybe a better way of achieving this without grep than I know?

amallard

Posted 2017-08-17T15:45:02.560

Reputation: 147

I found something else and removed my comment. – DrZoo – 2017-08-17T15:59:53.043

I'm not totally familiar with PowerShell but try this: cd $(ls | grep STRING). That's the last guess I have. Otherwise I'd use tab completion. I'd honestly find that to be easier than typing that command. I'm not entirely sure if this will work. Another question is, if you're on Windows 10, have you thought about using the built in Bash feature they now have? – DrZoo – 2017-08-17T16:09:14.120

That's not working either. I can't install any plugins on this machine, so I'm looking for an out-of-the-box solution – amallard – 2017-08-17T16:10:37.410

Right now I'm only concerned with a PowerShell solution. I just put that comment in there because I've often been working in Linux and wanted to know how to do something similar, so if there was a universal solution then that'd be nice. But for the sake of what I'm trying to do right now, just an out-of-the-box PowerShell solution – amallard – 2017-08-17T16:12:45.357

Answers

1

You didn't tell which PowerShell version you are using ($PSVersionTable) Tab completion was enhanced in the recent versions but works in all versions albeit different, depending on the host (Windows/MacOS/Linux)

This should do

gci abc*|sl
  • gci is the powershell alias for Get-ChildItem aka dir/ls
  • (On linux/macOS ls will revert to the system lsversion.)
  • sl is Set-Location similar to cd

LotPings

Posted 2017-08-17T15:45:02.560

Reputation: 6 150

Adding for future users: If you want to search for bcd (using my example) use: gci *bcd*|sl – amallard – 2017-08-17T19:54:15.630