0

I'm rather new to powershell and I couldn't find any documentation as to how to deal with the following issue. I just don't know how to word my question succinctly enough to produce any extremely relevant results on google.

Let's say I have a list of files in a directory:

$stuff = "file name1 1.csv", "file name2 78.csv", "file name3 14.csv"

"file name1 1.csv"
"file name2 78.csv"
"file name3 14.csv"

I would like to remove the first space after the word file and the second space after the word name, while also disregarding the .csv designation, leaving me with:

   "filename1"
   "filename2"
   "filename3"

I just want a list of these file names to loop over. I'd like to code this so I can generalize it to any group of filenames. Does anybody have any good ideas or can anyone point me in the right direction/documentation?

Thanks in advance.

EthanT
  • 99
  • 6
  • is there an actual directory with files, or just a list of filenames? – Withholm Jun 26 '20 at 22:19
  • In my situation, yeah, there is. I use `$group = (ls($path)).Name` to give me the "list" of files that I'm using. – EthanT Jun 27 '20 at 04:44
  • 1
    to add on to the solution below, you can use .basename to have JUST the filename without the extension, so you dont have to remove this later on :) – Withholm Jun 27 '20 at 09:41

1 Answers1

2

here's another way to get the job done. [grin]

what it does ...

  • creates an array of strings to work with
    if you are dealing with actual file objects, you will likely need to use the .Name or .BaseName properties of those objects.
  • puts that array into the $InStuff collection
  • iterates thru that collection
  • splits on the spaces
  • takes only the 1st & 2nd items from that split
  • joins the above items with no delimiter
  • sends them to the $OutStuff collection
  • displays that on screen

the code ...

#region >>> create an array of strings to work with
#    in real life, replace this block with your source instead
$InStuff = @'
file name1 1.csv
file name2 78.csv
file name3 14.csv
'@ -split [System.Environment]::NewLine
#endregion >>> create an array of strings to work with

$OutStuff = foreach ($IS_Item in $InStuff)
    {
    # take only the 1st two items
    #    join them with no delimiter
    -join $IS_Item.Split(' ')[0,1]
    }

$OutStuff

output ...

filename1
filename2
filename3
Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26