Question

i hope You can help me. I have a lot of csv files (90000) I need to change the filename with the name in the File. In this example i want to search the 13th delimiter of the second line where we find "020/NOT-232032/2013" and than rename the csv File by this name. Is there any way to make this with Powershell, VBS, cmd, or other way? please help thakx

example File1.csv --> 020-NOT-232032-2013.doc :

File1.csv

Line1:

"statoDoc","idDoc","tipoCliente","tipoDoc","idUtente","oraDoc","indirizzo","idTerminale","ragioneSociale","codiceFiscale","idClienteSede","idCessionario","nrDoc","dataFirma","localita","partitaIva","firmatario","idDestinatario","dataDoc"

Line2

"C","232032","","NOT","020","00:19","CASTELLO DI FE","020","PANI c","00624330221","200673","","020/NOT-232032/2013","2013.08.20","CASTE MME","IT00624330221","","102796","2013.08.20"

Was it helpful?

Solution

Here's two possible solutions using PowerShell:

Importing csv-data. Easier to read.

Get-ChildItem -Filter "*.csv" -Path "c:\folderwithCSVs" -Recurse | % {
    $filename = (Import-Csv $_.FullName)[0].nrDoc.Replace('"',"").Replace("/","-").Trim() + ".doc"
    Rename-Item -Path $_.FullName -NewName $filename
}

Using text-parsing. Recommended for large csv-files.

Get-ChildItem -Filter "*.csv" -Path "c:\folderwithCSVs" -Recurse | % {

    #Open file
    $reader = New-Object System.IO.StreamReader $_.FullName

    #Ignore first line
    $reader.ReadLine() | out-null

    #Get name
    $filename = $reader.ReadLine().Split(",")[12].Replace('"',"").Replace("/","-").Trim() + ".doc"

    #Close stream
    $reader.Close()

    #Rename file
    Rename-Item -Path $_.FullName -NewName $filename

}

OTHER TIPS

You need a plan.

  1. How to access the files? Can you just loop over the files in one folder? Traverse one folder tree recursively? More than one start directory?
  2. Given a file (object) - can you determine whether it should be processed? Extension? File name format? Already processed?
  3. For a file to be processed: Open, Skip first line, Read second line, Split on "," (risky if "," is valid data; maybe use a RegExp patterned for ,"020/NOT-232032/2013",), Transform field to name, Close, Rename
  4. Transform in VBScript:

wtf

>> fld = """020/NOT-232032/2013"""
>> nam = Replace(Mid(fld, 2, Len(fld) - 2), "/", "-") & ".doc"
>> WScript.Echo fld, "=>", ">" & nam & "<"
>>
"020/NOT-232032/2013" => >020-NOT-232032-2013.doc<

Here's a VBScript option:

Option Explicit
Dim objFSO 'File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objDir
Set objDir = objFSO.GetFolder("C:\MyFiles")
Dim objFile
Const ForReading = 1

For Each objFile In objDir.Files
    If(UCase(Mid(objFile.Name, InStrRev(objFile.Name, "."))) = ".CSV") Then
        Dim objFileTS
        Set objFileTS = objFSO.OpenTextFile(objFile.Path, ForReading, False)
        objFileTS.SkipLine()
        Dim strToken

        'Read the second line, split it into an array on the "," char, and get the
        '13th token in the array (array's are zero-indexed, so it's the 12th index).
        strToken = Split(objFileTS.ReadLine(), ",")(12)

        'remove quotes.
        strToken = Replace(strToken, Chr(34), "")

        'replace "/" with "-".
        strToken = Replace(strToken, "/", "-")

        objFileTS.Close()
        Dim strNewPath
        strNewPath = Left(objFile.Path, InStrRev(objFile.Path, "\")) & strToken & ".doc"    
        objFile.Move(strNewPath) 'move to the same place with a different name is the only way to rename.
    End If
Next

Here's a VBS solution that expands on @roryap's answer

Option Explicit

Const PATH = "C:\folder\where\csvs\sit"

Dim fso, file
Dim cn,rs
Dim val

Set cn = CreateObject("ADODB.Connection")
Set fso = CreateObject("Scripting.FilesystemObject")

'HDR = yes because your first row is data headers
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & PATH & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

For Each file in fso.GetFolder(PATH).Files
  Set rs = cn.Execute("Select * From [" & file.name & "]")

  Do While Not rs.EOF
    val = rs.Fields.Item("nrDoc").Value 

    If Not isNull(val) Then
      val = Replace(val,"/","")
      file.Move Left(file.Path, InStrRev(file.Path, "\")) & val & ".doc" 
      Exit Do
    End If

    rs.MoveNext
  Loop 

Next


WScript.Quit

When it finds a value in that 13th slot, it will use it then disregard the remainder of that CSV, and move onto the next CSV

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top