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.

3
  • is there an actual directory with files, or just a list of filenames? Commented Jun 26, 2020 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. Commented Jun 27, 2020 at 4: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 :) Commented Jun 27, 2020 at 9:41

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

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.