0

I have a list of directories with files like this:

testing_module/forms/node.js
terraform_packer/globals.js
protection_list/forms/security.js

I want to get with powershell only the folder before the slash:

testing_module
terraform_packer
protection_list

I use -replace with this regex expression to test it:

'testing_module/forms/node.js' -replace '/([^/]+/[^/]+)$'

But it returns the full line.

What should I use?

4
  • 1
    Are your strings literally what you presented or is there something before them like C:/myfolder/? Commented Feb 20, 2018 at 20:57
  • 1
    You forgot to add , '' at the end. 'testing_module/forms/node.js' -replace '/([^/]+/[^/]+)$', '' Commented Feb 20, 2018 at 20:58
  • @S.Jovan That doesn't actually matter, the substitution pattern defaults to an empty string if left unspecified Commented Feb 20, 2018 at 21:08
  • Your use case is ambiguous. You say you want only the folder before the file but your last example states it should output the name of the folder two folders above the file. Commented Feb 20, 2018 at 21:13

3 Answers 3

2

You could replace the first / and everything after with:

'testing_module/forms/node.js' -replace '\/.*$'

or use -split and grab only the first resulting part:

@('testing_module/forms/node.js' -split '/')[0]
# or 
'testing_module/forms/node.js' -split '/' |Select -First 1

or use the String.Remove() and String.IndexOf() methods:

$str = 'testing_module/forms/node.js'
$str.Remove($str.IndexOf('/'))
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution returns what I wanted !
2

I see that as matching rather than replacing. Match any character that's not a forward slash until you meet a forward slash:

'testing_module/forms/node.js' -match '[^/]+'
$matches[0]
'terraform_packer/globals.js' -match '[^/]+'  
$matches[0]
'protection_list/forms/security.js' -match '[^/]+'
$matches[0]

It works with folders of any depth.

Comments

0

I think it's nicer to positively search for what you are looking for rather than to remove what you are not looking for. Here we search from the beginning of the string for the biggest substring that doesn't contain a slash.

PS> "testing_module/forms/node.js" -match "^[^/]*"
True
PS> $matches[0]
testing_module

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.