Reputation: 97
I have a text file which contains file names and other text. If I filter the file with this:
Get-Content .\Movies.txt | Select-String volume
I get the output below. How can I modify the above command so the output is just the file names?
/volume1/Media Library/Movies/Poltergeist (2015).mp4
/volume1/Media Library/Movies/Goosebumps (2015).mp4
/volume1/Media Library/Movies/Hotel Transylvania 2 (2015).mp4
Upvotes: 0
Views: 300
Reputation: 8868
I'm curious to see how you made the text file in the first place, as there is probably a better way to store/extract the data you're after. However, to address your specific question I propose two options. If you can provide more detail of what the "other text" is, then this answer may be improved.
Option 1
Use split on '/` and grab the last element.
'/volume1/Media Library/Movies/Hotel Transylvania 2 (2015).mp4'.Split('/')[-1]
Hotel Transylvania 2 (2015).mp4
or
('/volume1/Media Library/Movies/Hotel Transylvania 2 (2015).mp4' -split '/')[-1]
Hotel Transylvania 2 (2015).mp4
Option 2
Use a regex pattern to extract the filename.
'/volume1/Media Library/Movies/Hotel Transylvania 2 (2015).mp4' -replace '^.+/(?=.+)'
Hotel Transylvania 2 (2015).mp4
To apply any of these in a loop you can use the Line
property of the returned match.
Get-Content .\Movies.txt | Select-String volume | foreach {$_.line.Split('/')[-1]}
However the switch statement can both read the file and process line by line.
Switch -Regex -File (".\Movies.txt")
{
'volume' {$_.Split('/')[-1]}
}
Poltergeist (2015).mp4
Goosebumps (2015).mp4
Hotel Transylvania 2 (2015).mp4
Upvotes: 1
Reputation: 61028
Here's three more ;)
[System.IO.Path]::GetFileName('/volume1/Media Library/Movies/Poltergeist (2015).mp4')
and
'/volume1/Media Library/Movies/Poltergeist (2015).mp4'.Substring('/volume1/Media Library/Movies/Poltergeist (2015).mp4'.LastIndexOf("/") + 1)
and
'/volume1/Media Library/Movies/Poltergeist (2015).mp4' -replace '.*/(.+)$', '$1'
Upvotes: 1
Reputation: 15480
I can use Split-Path
here:
(Get-Content .\Movies.txt | Select-String volume) | ForEach {split-path "$($_)" -Leaf}
Upvotes: 1