Find files by name who match string

Need to cycle through all files in a folder who have same string in thier respective names

String_1_1.txt
String_1_2.txt
String_1_3.txt
AnotherString_1_1.txt
AnotherString_1_2.txt

Then pass all matching file names to a a new string for each match as
String_1_1.txt+String_1_2.txt+String_1_3.txt AS String.txt
AnotherString_1_1.txt + AnotherString_1_2.txt AS AnotherString.txt

And this would go through all files in a folder.
ayacko2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

meraydin2Commented:
Something like this?

Imports System.IO
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()


        Dim pattern As String = "string"
        Dim replace As String = "new_string"

        Dim files() As String = Directory.GetFiles("c:\test", "*.*", SearchOption.TopDirectoryOnly)
        For Each file As String In files

            If Regex.IsMatch(file, pattern) Then

                Dim newName As String = Regex.Replace(file, pattern, replace)
                System.IO.File.Move(file, newName)

            End If

        Next

    End Sub

End Module

Open in new window

0
meraydin2Commented:
P.S. pattern and replace can be plain text or full featured Regular Expressions. For example:

Pattern: string\d*\sTest
Replace: my_newstring

replaces allfiles which starts with "string" then anynumber of digits then a whitespace and "Test" with "my_newstring"

0
ayacko2Author Commented:
Sorry...  can't see how to edit my original question.

I have a folder of files and the names will always change. The script needs to read first 10 characters of a file name and find any other fille with the same 10 character string. (All characters before the "_")

Once it finds all files with the same character string then output those as

"samestring_1+samestring_2+samestring+3"

and then check the next file.

If there is no match available then i would like to just remove everything after  the underscore in the file extension.
0
How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

meraydin2Commented:
What do you mean by saying "output those as"? Will it copy those files to some other place? Will it display the file names?
0
Chris DentPowerShell DeveloperCommented:

Are you hoping for this in PowerShell?

If so, and depending a little on how your names are structured this works:

Get-ChildItem "C:\SomeFolder" | Select-Object *, @{n='NamePart';e={ $_.Name.Split("_")[0] }} | Group-Object NamePart

I'm not certain how you want the output really, or even if you wanted PowerShell.

Chris
0
ayacko2Author Commented:
Thanks for the assistance so far. We want to do this in Powershell for those who inquired. These are pdf files and we have a command line executable that can merge them. The objective is for each set of matching filename(s) pass a string to the merge program.

Chris your suggestion kicks back some errors "Namepart" not a valid cmdlet

Here is what needs to occur

1) For each file in the folder search remaining files to find any that matches it's substring $_.name.substring(0,15)
2) Create a string output of matching files as "matchingstring_1_1.pdf+matchingstring_1_2.pdf merge as matchingstring.pdf"
3) If the search doesn't find another matching file it would simply rename the file by removing anything after the underscore (rename-item -newname {$_.name.substring(0,15)+".pdf"})

0
Chris DentPowerShell DeveloperCommented:

NamePart might do that if you missed out the comma between * and the NamePart property we're attempting to add.

Anyway, try this one. If you want to test without actually renaming files add "-WhatIf" onto the end of the Rename-Item line.

HTH

Chris
Get-ChildItem "C:\SomeFolder" | `
  Select-Object *, @{n='NamePart';e={ $_.Name.SubString(0,15) }} | `
  Group-Object NamePart | %{
    If ($_.Count -eq 1) {
      Rename-Item $_.Group[0].FullName -NewName "$($_.Group[0].NamePart).pdf"
    } Else {
      Write-Host $([String]::Join("+", $($_.Group | %{ $_.Name })))
    } }

Open in new window

0
ayacko2Author Commented:
The processing works great. There is an issue trying to pass your write-host line to the exe that does the document merge. I'm using pdftk to merge these but it won't execute within Powershell

I have the following
$tool = "pdftk"

Else {
              
      $cmd = "$([String]::Join(' ', $($_.Group | %{ $_.Name }))) cat output $($_.Group[0].NamePart).pdf"

cmd /c "$tool $cmd"
    } }

I get the following error

Error: Failed to open PDF file:
   Filename.pdf
Errors encountered.  No output created.
Done.  Input errors, so no output created.
0
Chris DentPowerShell DeveloperCommented:

Check the contents of $cmd first? It's possible something unexpected crept in there.

Chris
0
ayacko2Author Commented:
Everything is good there. I can actually write the output to a txt file and copy and paste them into a CMD window and it works.

Just not sure why PowerShell can't process them. I've also tried versions of Invoke-Expression and Invoke-Item with no luck
0
Chris DentPowerShell DeveloperCommented:

If you copy it and paste it back into the PS window does it still complain? I would expect it to but it's always nice to make sure.

What characters does it have left in the string? If it happened to include another $ anywhere it might mess up quite a lot for instance.

Chris
0
ayacko2Author Commented:
It works within PowerShell
cmd /c pdftk fileone_1.pdf filetwo_2.pdf cat output newfile.pdf

The process assembles the correct statement for each set of file but can't seem to execute the statement to merge for each set.

0
Chris DentPowerShell DeveloperCommented:

Send the line to a batch file and try executing that?

Chris
0
ayacko2Author Commented:
I output the commands to a txt file renamed it .bat and it won't fire.

' []p'  is not a recognized  as an internal or external command, operable program or batch file.

Some character is getting inserted before each line.
0
Chris DentPowerShell DeveloperCommented:

Can you try...

"$([String]::Join(' ', $($_.Group | %{ $_.Name }))) cat output $($_.Group[0].NamePart).pdf" > "temp.bat"
cmd /c temp.bat

Chris
0
ayacko2Author Commented:
It's trying to process it but there is some ¦ character still being inserted at the begining of each line which won't allow the command to run.

'¦p' is not recognized as an internal or external command,
operable program or batch file.
0
Chris DentPowerShell DeveloperCommented:

I was hoping you'd be able to see that in the batch file?

Chris
0
ayacko2Author Commented:
Nothing shows in the bat file itself. I can copy and paste the commands into PS or CMD and they work fine, but reading directly from the file it won't

I did open the file in a HEX editor and i can see there is a space and then a square character. Just not sure how to write this file without including these
0
Chris DentPowerShell DeveloperCommented:

Back to the beginning a bit. I put the part you're trying to run into the original. Can we give this a try?

Chris
Get-ChildItem "Temp" | `
  Select-Object *, @{n='NamePart';e={ $_.Name.SubString(0, 15) }} | `
  Group-Object NamePart | %{
    If ($_.Count -eq 1) {
      Rename-Item $_.Group[0].FullName -NewName "$($_.Group[0].NamePart).pdf"
    } Else {
      # Create the Command
      $Cmd = "cmd /c pdftk $([String]::Join(' ', $($_.Group | %{ $_.Name }))) cat output $($_.Group[0].NamePart).pdf"

      # Execute the Command
      Invoke-Expression $Cmd
    } }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ayacko2Author Commented:
TOUCH DOWN !

Nice Work!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.