Splitting file name !!
Hi,
Suppose I have a filename as abc_lmn_123.log and I need to split this name into 3 different variables - which command should i use.
My OS is Solaris 5.8
Thanx
Sumit
Not sure to understand. Check this out :
$ set `echo abc_lmn_123.log | awk -F_ '{print $1, $2, $3}'`
$ echo $1 $2 $3
abc lmn 123.log
$ You could also try
$ echo abc_lmn_123.log | awk -F_ '{print $1, $2, $3}' | read F1 F2 F3
$ echo $F1 $F2 $F3
Similar Messages
-
Splitting file names using delimiter question
I have a very simple question. I am trying to set the variable $fnameYear to whatever is after the third '-'. My problem is that if there is a space in the name it wont work correctly. How can i use a delimeter so that it splits after the '-' for only 4
characters?
$fnameYear=(($_.BaseName -split '-')[3])This should work:
$_.BaseName.Split('- ',[System.StringSplitOptions]::RemoveEmptyEntries)[3]
¯\_(ツ)_/¯ -
Hallo,
ich habe einen Filenamen, der folgendermassen aufgebaut ist: aaaaaa__bbbbbb_d__cc_ddd__ee_ff_gg_hh__iii......... Der Name soll nun jeweils bei doppelter Underline getrennt werden und die Werte jeweils in eine Variable geschrieben werden. Dies sieht dann wie folgt aus:
Textvariable 1: aaaaaa
Textvariable 2: bbbbbb_d
Textvariable 3: cc_ddd
Textvariable 4: ee_ff_gg_hh
Die Länge des Namens sowie die Anzahl doppelter Underline variiert.
Kann mir jemand weiterhelfen, wie ich das in Diadem Script am einfachsten hinkriege?
Vielen DankHallo siipo!
am einfachsten ist die Verwendung des VBS Befehls Split der sein Ergebnis in ein Array speichert. Das Beispiel gibt das Ergebnis aus:
Option Explicit
Dim sgName
Dim asgNames
asgNames = Split( "aaaaaa__bbbbbb_d__cc_ddd__ee_ff_gg_hh__iii","__")
MsgBox UBound(asgNames)+1 & " Teile gefunden"
For Each sgName In asgNames
MsgBox sgName
Next
Matthias
Matthias Alleweldt
Project Engineer / Projektingenieur
Twigeater? -
File name in Split messages with Message mapping
Hi everyone,
I split my incoming message into multiple files based on the Order Numbers.
Also I have a particular file naming convention I need to use.
Its someething like RTG746932746.63749
Now, I have given the field file name along with my target data type and mapped it like the format i want alogn with order Number to make it unique.
But when I dwnload files, I get only one file.
Whereas if I just use the option, Add time stamp in the communication channel, it works fine, giving me 3 order files if i have 3 orders.
But I cannot have ' -' in my file name.
How do i resolve this?
Thanks,
Vinotha MIs teher any thing else I can do change the file name and have mulitple files downloaded without it being overlapped.
Please help resolve
Thanks,
Vinotha M
Edited by: Vinotha M on Feb 4, 2009 4:10 PM -
Split PDF and use field name for file name
I have a pdf file with 333 pages that I will be splitting into 333 separate pfd files. Each file needs a specific name that corresponds to a number located in the header of each individual page.
Splitting the pdf is easy, unfortunately I can only use a static name for part of the file name and Adobe assigns the remaining portion with: _Part1.pdf; _Part2.pdf ect.... How can I get the "_Part1" to pull in the number located in the header of each individual page?
I need to have this done before tommarow morning and there is another PDF which will be 555 files after it is split.
Thanks for any help!Yes,
I also know Profit Center field from R/3.
However as I've mentioned....
I need to ADD the field "Profit Center" in this TAB
I do not even know if this field "Profit center" that I need to ADD is the same field from R/3.
<b>You know....</b>
I found "Profit Center"
screen number: 0200
program name: SAPLCRM_1O_MANAG_UI
structure: ZCRMT_0200_BTX_UI01
field name: ZZCUSTOMER_I0101
data element: ZEEW_DATAELEMENT0101
<b>However...</b>
If I add this field above, the field does not display in the TAB I want. Meaning this field is not working.
<b>For Instance:</b>
In the same TAB (I want to add Profit Center), I have the field with:
- description name field "Services Revenue"
By pressing F1/Tech Info, I have:
screen number: 0200
Program name: SAPLCRM_1O_MANAG_UI
Structure: ZCRMT_0200_BTX_UI01
Field name: ZZCUSTOMER_I0101
Does anyone has any idea to help me outto fimd Profit Center field?
many thanks,
Barb -
Need to validate file Name,split the file name and store the splited values into Variables
Dear All,
Below is the my requirement.
I have a folder, in that folder I have bunch of text files. The file name is below format
ACA_122_pay_20140430_001
Initially the file name start with ACA code,groupid,group name and date time stamp. This is the standard structure of file name.
I want to check each and every file in the folder with this structure. The structure should be standard for all the files. If the structure same for all files I need to get codes form file name. For example
If you see the below file name, I need to get ACA and put into variable,I need to get 122 and put into variable. For group name and date time needs to put in variable.
If the file format is not valid state then I need to log exception.
Let me know if I am not clear.
Kindly provide the C# code for achieving the above requirement.
As I am new to .net programming. kindly help me.
Thanks in Advance,
Regards,
Madhava Ganji
Madhava GanjiHi MadhavaGanji,
I have post how to validate the file name, header row against definition table which stored the file name and column definition.
Take a look and see if this is helpful.
http://sqlage.blogspot.com/2013/11/ssis-validate-file-header-against.html
http://sqlage.blogspot.com/ -
Print to PDF and specify file name.
Hardware/Software Details:
MacBook 2GHz Intel Core 2 Duo
OS 10.5.5
Adobe Acrobat Professional 8.1.2
Hey all,
I'm a teacher and I've been scripting PDFs for use as marking sheets for assignments. What I'm trying to achieve is a situation where I tick all the boxes, marks are calculated and comments filled-in using my form fields (which all work fine) and then produce a PDF from that file with the student's name as the new file name (which is where I'm stuck!).
In the past, I've had a button that on mouseOver brings the field with the student's name into focus, mouseDown evoked the File:Copy menuItem (copying the student name to the system's clipboard) and then mouseUp which triggered File:Print from which I would choose 'Adobe PDF 8.0' as the printer, hit Save, paste the student's name as the file name and choose the appropriate directory.
File:Copy is no longer a "safe" menu item according to the latest versions of Acrobat, so I'm having to manually copy the name which is complicating the process further.
I'm working on a script activated by the mouseUp of a button in this PDF which is currently looking like this:
>var pp = this.getPrintParams();
// format name to remove spaces and commas
var studName = this.getField("Name").value.split(",").join("_").split(" ").join("");
pp.interactive = pp.constants.interactionLevel.silent;
pp.printerName = "";
pp.fileName = studentName + ".ps";
this.print(pp);
Although the console will list 'AdobePDF8' as one of my printers, I've since discovered that "the destination printer cannot be set through this property in Mac OS" :( . I can set it as my default printer to work around it, but I still can't dictate the name of the new file. So, I've resorted to printing to PostScript with the aim of running them all as a batch through the AdobePDF8 printer later, except there's still a few problems.
The name of the PostScript file won't work when I try to include the value of another variable (var studentName)
The fonts in the PostScript files that it does produce get substituted with Courier and look terrible
Both the API Reference and the Developer Guide seem to indicate that you can print to a file rather than a printer, but both only seem to mention PostScript file using this method.
Is there another way to do this? If not, is there a solution to the two problems I mentioned?
Cheers,
ChrisOk, I've pursued the SaveAs method (as George suggested) with moderate success with the following code (secure function names have been changed ;) ):
config.js file script:
>myTrustedSaveAs = app.trustedFunction( function ( doc, studName )
app.beginPriv();
doc.saveAs({
cPath: studName,
bCopy: true,
bPromptToOverwrite: true
app.endPriv();
myTrustedOpenDoc = app.trustedFunction( function ( path )
app.beginPriv();
app.openDoc({
cPath: path
app.endPriv();
Button's onMouseUp script:
>// get student name and turn it into a file name
var studFile = this.getField("Name").value.split(",").join("_").split(" ").join("") + ".pdf";
// get the current document's directory path
var origFile = this.path;
var pathBits = this.path.split("/");
pathBits.pop();
// whack 'em together
pathBits.push(studFile);
var studFilePath = pathBits.join("/");
// toss the form fields and stuff
this.flattenPages({
nNonPrint: 2
// save the new file
myTrustedSaveAs(this,studFilePath);
// open the original again (not working)
myTrustedOpenDoc(origFile);
// close the one I just saved
this.closeDoc(true);
This is what happens:
Button is clicked,
All the form fields and buttons are removed,
It produces a file with the new file name (e.g. Lawrence_Chris.pdf) next to the original,
The file closes
I'm pretty sure that once the SaveAs runs and the new file is created, I actually still have the original file open instead of the that was just saved. This would explain why the openDoc command doesn't seem to do anything because the file it's opening is already open. The closeDoc then runs and of course I then have no open documents!
So, now I either need a way to revert the open original file so I get all of my form fields back and don't have to reopen it, or a way to close and then immediately open the file without saving changes. :/
Any ideas?
slight inconvenience of needing a separate .js file written for the user's JavaScript folder before launching Acrobat to overcome security restrictions. File sizes only seem to get down to about 376KB as opposed to the 40KB files that the AdobePDF8 printer spits out. :( -
I planned on kicking off my journey attempting to edit a massive multi year documentary on FCPX with a nice introduction of the blog I'm going to keep about the experience, but I've run into a bit of a roadblock, or maybe major speed bump at least before even getting to that point. I wanted to share what is working as a work around for me and you guys can tell me how I'm doing it wrong.
Ok, I will try to explain this as succinctly as possible. I'll write in somewhat stream of consciousness just to try and get through it quicker... Basically, after discovering the work around below, I am now utterly confused on how FCPX handles the relationship between its own database of where media is stored, and the actual media itself. I have plenty experience on FCPX now, probably done 30-40 pro commercial jobs on it over the last year since XML became doable as I'm also a Resolve Colorist and all the FCPX projects where hardcore coloring product spots. For commercial work, I never needed to worry about splitting up footage up over multiple Events. Everything, all in one, FCPX handled it no problem. (well the occasional beach ball, but that seems to be a thing with FCPX in general)
This will be my 10th feature documentary as an Editor. Every one before it was either on Avid's many flavors over the last 12 years or FCP Studio. When this new film came along, I made the decision a few months ago to use FCPX for a few reasons, but mostly because I'm insane and I like to try to mix it up for myself in a career that can get stale quick if you aren't willing to be that way. The film was shot over 2+ years, every shoot was multi cam 5D (yes i know, looks great, but please kill me), I haven't done the math on length, but there is over 10,000 clips of video (this is actually medium in size compared to what I've dealt with before). Its 5D, so theres external audio for everything. FCPX's syncing is great, but I've learned that theres an unsaid window of heads and tales clips must fall within to sync properly with the nearby clips, if they are too far apart FCPX gives up. One shoot day could have 3 cams, 50 clips each, and 2 audio files to sync to, FCPX simply cannot handle this, so off to Plural eyes they went, no problems.
Ok, all this is relevant eventually I swear! Again, in the past, all in one event, no problem. I tried for fun to bring all media into one Event on this film. It worked, but there is a 10+ second spinning beach ball for every single move you make, so thats no good. Ok, I'll separate the Events out to, lets say, each shoot month. Well that's dumb, in verite documentary, any shot could be the first, any shot could be the last, you need a command over all searchable footage at all times. Shift selecting all events to search *****, and it actually takes longer for FCP to reload each event each time than it does to just have the one massive one. So no go there. Next hair brained idea... What if make a new Event that is just Compound Clips of all the other Event's contents and do more with Markers and Favorites in logging that I was planning to parse it all out. That way I'm working with and FCPX is dealing with 50-60 clips instead of 10,000+ Quick test, Cmd-A, Opt-G, boom, boom, boom, move all to dedicated to Event, hide huge Event, BEHOLD, that works! FCPX chokes a little bit on the insane length of some of the clips, but searching, and general performance is back on par!
So your saying to yourself "Ok *********, sounds like you figured it out, what's the problem." Well to you I say, "Not so fast!" Remember, that was just a quick test using the media I had imported into the massive 10,000+ clip Event. To do this project proper, I am having to import Multicam sync'd XMLs from Plural Eyes. And this is where it all starts to fall apart. A little foreshadowing for your eager eyes. 10,000+ files all shot with multiple 5D's over the course of years. What does that mean? many, many duplicate file names!
FCPX as well all know irritatingly imports XML's as new Events, not into existing ones. This obviously takes a lot of burden off media management because with a new Event comes a new database referencing its own version of the raw media. All well and good, and I'm betting its starting to click for some if you advanced users where I'm finally going with this. So I have 50 or so XMLs to bring in, all done no problem. Now I want to replicate that singular Event like I did with the Compound Clip test and have it all in one place to be my master as extensive logging begins for easy searching once editing begins. Highlight the Events, click Merge Events. NOPE. I get a new "Kill Yourself Now" error (a term I coined for Out of Memory and General Error messages in FCP Legacy meaning there ain't much you can do about it): "Two or more files have the same name. Change the names and try again, because I don't know what the **** to do with them." Ok I made up that last part but that's basically what it's saying. Just take the variable out of the equation, this happens with every which way you could try to get the clips together. Merge Events, dragging events on top of each other, dragging just the Multicam clip alone, nothing gets passed that message. What's worse is that while Batch Renaming seems like a solution, the renames do not populate inside the created clips and there is no way to Batch Rename those. Renaming everything at the finder level isn't so great because then I'd have to resync and theres an offline/online thing going here where the film has to be reconformed eventually.
Basically, I've found that FCPX handles media management in completely different ways depending on whether you are importing into one Event yourself or doing essentially what is a new import with FCPX moving or merging Events. If you bring in all the media to one Event, on a macro level FCPX goes through file by file making aliases referencing the master file. If it hits a duplicate, it makes a parenthesis counter, and keeps going. And with the genius of FCPX metadata, that file name doesn't even matter, you can change it at the Finder level and FCPX will keep the link intact. BUT for some reason if you try to do this outside the realm of a single Event and combine files after the fact a different process takes over in creating this database system and can't handle the duplicates. I can't totally figure the reason other than it probably is scared to change the originally referenced alias to something else (which it shouldn't be scared of since Merge Events deletes the original anyway).
This is where it gets INSANE and where I lose all understanding of what is going on, and believe me it was a delicate understanding to begin with. It comes in to play with the work around I figured out. I make the master Event with the 10,000+ clips. Then I import all the XMLs as dedicated Events. Now, I then drag the Multicam clips into the master Event, it WORKS! just takes it, no "Kill Yourself Now" error. Stranger still, now with the switched referenced Event, it even takes into account which aliased duplicate file name it's referencing in the Original Media folder. Somehow, it's taking into account the original file path and saying "Ok, I see 5 instances of MVI_5834.mov. Based on the original file path or maybe creation date or god knows what, it must be MVI_5834 (fcp3).mov." It connects perfectly. I can even remove the old XML imported Event with no problem. Crazier yet, I can now move those again to the dedicated Event I wanted originally that only contains those Multicam or Compound Clips.
So instead of going straight from A to C, going from A to B to C works even though that actually seems way more complicated. Why can't FCPX handle Merge Events and dragging clips the same way it handles media imported into a single Event. And weirder still, why can't FCPX handle the (fcp1,2,3...) appending in the same scenario. But if the appended links are already there, No Problem. And for the love of god, it'd be nice to important XML's into existing Events and make the correct referencing happen right from the get go, which is really the source of all the above headache. I'd have no problem helping FCPX with a little manual pointing in the right direction just like any other NLE needs.
Ok, having said all of that crap above, my question is, have I missed something completely simple I should have done instead? Now that I have everything in place how I originally envisioned, I think I will still play around a little bit more to make sure FCPX is really going to be able to handle this project. I'm at a stage right now where going another direction is still an option, although the dare devil in me wants to make this work. Media management aside, once you start editing on a FCPX timeline, its hard to go back to anything else. Apple is going to have to figure out some way not to access to everything at all times to work fluidly or big projects like this are never going to be practical in FCPX.
Sorry for the long confusing post....I'm having the exact same problem, but I know nothing of ruby scripts. I've exhausted my resources with tech support, and after literally hours of work with them it seems I now am faced with either re-rating each individual song, or pointing iTunes to each song that it can't locate. Is yours a solution that could help me? How can I find out more about Ruby Scripts? Thanks for your help, hellolylo (or anyone else who might also be able to help...)
Kenn -
How to user PowerShell -replace to remove the dreaded em dash from a file name?
I have a bunch of .msg files in a directory and want to zip them up (to send them to our spam filtering company), but I keep getting errors on file names that contain the em dash (—). I believe it's (char)0x2014.
[edited]... the correct syntax is [char]0x2014.
I wish to eliminate the em dash in the file name but I can't seem to find anything on the web about replacing em dashes. When I paste '—', PowerShell replaces it with a '-'.
I found this neat function that does a great job replacing multiple characters within a string.
http://powershell.com/cs/blogs/tobias/archive/2011/04/28/multiple-text-replacement-challenge.aspx
I am using the below code for my string replacement.
Thank you for your help.
function Replace-Text {
param(
[Parameter(Mandatory=$true)]
$text,
$replacementlist = "(-,,',,%,,$,,@,,#,,&,,’,"
Invoke-Expression ('$text' + -join $(
foreach($e in $replacementlist.Split(',')) {
'.Replace("{0}","{1}")' -f $e, $(
[void]$foreach.MoveNext()
$foreach.Current)
$path = '<path>'
Get-ChildItem -Path $path | Rename-Item -NewName {(Replace-Text $_.Name).trim()}Here is a simple filter that will strip out all nonprintable chanracters.
$newname=$file.Name -replace '[^a-zA-Z\.]'
I just tested it on Win 7 which supports has a Unicode filesystem and it successfullstrips the bad characters.
We also need to do this on files uploaded to SharePoint and OneDrive.
The ~ and other similar characters are not allowed in may systems. You should keep a translation log and tag all renamed files with some obvious tag.
¯\_(ツ)_/¯ -
Import From Folder: How to Extract the File Name in a Custom Column.
Hello All
Here´s what we´re trying to do:
We have a folder with csv files named like this:
Sales_2013-02-05.csv
Sales_2013-02-04.csv
Sales_2013-02-03.csv
Sales_2013-02-02.csv
Sales_2013-02-01.csv
And in the csv files there are the sales columns but not the date column.
So we want to extract the date from the file name.
I´ve tried entering = Source[Name] in a custom column, but it adds a "LIST" link, and on a click on expand, it adds ALL file names from the folder in each row, instead of just the needed one.
If we could get the proper file name in each row (from where they got extracted), we could split the column and get the date from there. But I don´t know how put the filename there properly.
Can you help?This isn't entirely straightforward, but it's definitely possible. What you need to do is to apply all of your transforms to each individual file instead of the combined files. I do that as follows:
1) Use Folder.Files as generated by the GUI to look at the list of my files.
2) Pick one file and do all the transformations to it that I want to apply to all of the files. Sometimes, this just amounts to letting the autodetection figure out the column names and types.
3) Go into the advanced editor and edit my code so that the transformations from step 2 are applied to all files. This involves creating a new function and then applying that function to the content in each row.
4) Expand the tables created in step 3.
As an example, I have some files with names that match the ones you suggested. After steps 1 + 2, my query looks like the following:
let
Source = Folder.Files("d:\testdata\files"),
#"d:\testdata\files\_Sales_2013-02-01 csv" = Source{[#"Folder Path"="d:\testdata\files\",Name="Sales_2013-02-01.csv"]}[Content],
#"Imported CSV" = Csv.Document(#"d:\testdata\files\_Sales_2013-02-01 csv",null,",",null,1252),
#"First Row as Header" = Table.PromoteHeaders(#"Imported CSV"),
#"Changed Type" = Table.TransformColumnTypes(#"First Row as Header",{{"One", Int64.Type}, {"Two", type text}, {"Three", type text}})
in
#"Changed Type"
For step 3, I need to take steps 3-5 of my query and convert them into a function. As a check, I can apply that function to the same file that I chose in step 2. The result looks like this:
let
Source = Folder.Files("d:\testdata\files"),
Loader = (file) =>
let
#"Imported CSV" = Csv.Document(file,null,",",null,1252),
#"First Row as Header" = Table.PromoteHeaders(#"Imported CSV"),
#"Changed Type" = Table.TransformColumnTypes(#"First Row as Header",{{"One", Int64.Type}, {"Two", type text}, {"Three", type text}})
in
#"Changed Type",
#"d:\testdata\files\_Sales_2013-02-01 csv" = Source{[#"Folder Path"="d:\testdata\files\",Name="Sales_2013-02-01.csv"]}[Content],
Loaded = Loader(#"d:\testdata\files\_Sales_2013-02-01 csv")
in
Loaded
Now I apply the same function to all of the rows, transforming the existing "Content" column into a new value:
let
Source = Folder.Files("d:\testdata\files"),
Loader = (file) =>
let
#"Imported CSV" = Csv.Document(file,null,",",null,1252),
#"First Row as Header" = Table.PromoteHeaders(#"Imported CSV"),
#"Changed Type" = Table.TransformColumnTypes(#"First Row as Header",{{"One", Int64.Type}, {"Two", type text}, {"Three", type text}})
in
#"Changed Type",
Transformed = Table.TransformColumns(Source, {"Content", Loader})
in
Transformed
Finally, I need to expand out the columns in the table, which I can do by clicking on the expand icon next to the Content column header. The resulting query looks like this:
let
Source = Folder.Files("d:\testdata\files"),
Loader = (file) =>
let
#"Imported CSV" = Csv.Document(file,null,",",null,1252),
#"First Row as Header" = Table.PromoteHeaders(#"Imported CSV"),
#"Changed Type" = Table.TransformColumnTypes(#"First Row as Header",{{"One", Int64.Type}, {"Two", type text}, {"Three", type text}})
in
#"Changed Type",
Transformed = Table.TransformColumns(Source, {"Content", Loader}),
#"Expand Content" = Table.ExpandTableColumn(Transformed, "Content", {"One", "Two", "Three"}, {"Content.One", "Content.Two", "Content.Three"})
in
#"Expand Content"
From here, you should be able to get to what you want. -
Is it possible to know the file name of images loaded?
Hi:
I have a folder containing some images named 01_image_name.jpg, 02_image_name.jpg, 03_image_name.jpg, ... wich names I read with a PHP script. Then I loop loading each image and waiting until all are loaded to display them
1. The PHP script reads file names and returns a string with names separated by a "|" char, then I use the split method to store them in imagesNames array and sort it
2. I loop trough imagesNames array loading images
3. Anytime a new image arrives I push it in imagesContainer array and check if all images are loaded to show them
The problem is there's no guarantee they arrive in the same order they were requested. So, how I sort the imagesContainer array by file name, i.e. in the same order they are in imagesNames array?
Thanks in advanceif you know when a new image arrives and you can retrieve that new image file name ...
Well, that's precisely my doubt, how can I know the file name? Is there a property/method for it?
function loadImages() {
for (var i:int=0; i<imagesNames.length; i++) {
var imgLoader:Loader=new Loader;
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,imgLoaded);
imgLoader.load(new URLRequest(imgPath + imagesNames[i]));
function imgLoaded(par:Event):void {
trace(par.target,par.target.content,par.target.content.name);
Output window:
[object LoaderInfo] [object Bitmap] instance160
[object LoaderInfo] [object Bitmap] instance159
[object LoaderInfo] [object Bitmap] instance161 -
Identifying text file names and importing on single Excel sheet
Hey!
Does anybody can help me with Excel VBA macro code in order to import data from text files into single Excel spread sheet? I want to create User Form where user can select start and end date of interest and macro code will import
bunch of text files depending on user demands...
My text files are named: 20130619004948DataLog.txt (meaning: yyyy mm dd hh mm ss). Text file contains recordings for each 15 seconds... It would be great to omit time tail (meaning that user can only specify date). Text files for one day of interest (I have
text files covering whole year):
20130619004948DataLog.txt
20130619014948DataLog.txt
20130619024948DataLog.txt
20130619034948DataLog.txt
20130619044948DataLog.txt
20130619054948DataLog.txt
20130619064948DataLog.txt
20130619074948DataLog.txt
20130619084948DataLog.txt
20130619094948DataLog.txt
20130619104948DataLog.txt
20130619114948DataLog.txt
20130619124948DataLog.txt
20130619134948DataLog.txt
20130619144948DataLog.txt
20130619154948DataLog.txt
20130619164948DataLog.txt
20130619174948DataLog.txt
20130619184948DataLog.txt
20130619194948DataLog.txt
20130619204948DataLog.txt
20130619214948DataLog.txt
20130619224948DataLog.txt
20130619234948DataLog.txt
Option Explicit
Sub SearchFiles()
Dim file As Variant
Dim x As Integer
Dim myWB As Workbook
Dim WB As Workbook
Dim newWS As Worksheet
Dim L As Long, t As Long, i As Long
Dim StartDateL As String
Dim EndDateL As String
Dim bool As Boolean
bool = False ' to check if other versions are present
StartDateL = Format(Calendar1, "yyyymmdd")
EndDateL = Format(Calendar2, "yyyymmdd")
' I am using Userform asking user to select the date and time range of interet,
' However, I want to use only the date to filter the files having the name with that particular date
file = Dir("c:\myfolder\") ' folder with all text files
' I need assistance with the following part:
'1) How to filter and select the files between StartDateL and EndDateL_
'(including files with that dates as well)?
While (file <> "")
If InStr(file, StartDateL) > 0 Then 'Not sure if the statements inside parenthesis is correct
bool = True
GoTo Line1:
End If
file = Dir
Wend
Line1:
If Not bool Then
file = "c:\myfolder\20130115033100DataLog.txt" 'Just for a test that the code works as intended
End If
'This part for the selected text files to be loaded on a single Excel Sheet.
Set myWB = ThisWorkbook
Set newWS = Sheets(1)
L = myWB.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row
t = 1
For x = 1 To UBound(file)
Workbooks.OpenText Filename:=file(x), DataType:=xlDelimited, Tab:=True, Semicolon:=True, Space:=False, Comma:=False
Set WB = ActiveWorkbook
WB.Sheets(1).UsedRange.Copy newWS.Cells(t, 2)
t = myWB.Sheets(1).Cells(Rows.Count, "B").End(xlUp).Row + 1
WB.Close False
Next
myWB.Sheets(1).Columns(1).Delete
Application.ScreenUpdating = False
Rows("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub- Make a new Excel file
- Open the VBA editor
- Add a Userform
- Place 2 text boxes and 1 command button on that form
- Paste all code below into the code module of the form
- Download this file:
https://dl.dropboxusercontent.com/u/35239054/FileSearch.cls
- In the VBA editor press CTRL-M and import that file
- Save the Excel file in the directory that contain your text files
- Run the form
You can format the columns of the sheet as you like, e.g. column E:H should be a number with 5 decimal places. The top row can contain some headings. My code did not affect the formatting or the headings.
Andreas.
Option Explicit
Private Sub UserForm_Initialize()
'Just a sample
Me.TextBox1.Value = FormatDateTime(Now, vbGeneralDate)
Me.TextBox2.Value = FormatDateTime(Now, vbShortDate)
End Sub
Private Sub CommandButton1_Click()
Dim StartDate As Date, EndDate As Date
Dim FS As New FileSearch
Dim R As Range
Dim ThisFile As Variant
Dim ThisDate As Date
Dim Data As Variant
Dim Count As Long
'Be sure we have 2 dates
If Not IsDate(Me.TextBox1.Value) Then
Me.TextBox1.SetFocus
MsgBox "No start date"
Exit Sub
End If
If Not IsDate(Me.TextBox2.Value) Then
Me.TextBox2.SetFocus
MsgBox "No end date"
Exit Sub
End If
'Convert to real dates
StartDate = CDate(Me.TextBox1.Value)
EndDate = CDate(Me.TextBox2.Value)
'Time part given?
If Fix(EndDate) = EndDate Then
'No include all files for this day
EndDate = EndDate + TimeSerial(23, 59, 59)
End If
'Correct order?
If StartDate > EndDate Then
ThisDate = EndDate
EndDate = StartDate
StartDate = ThisDate
End If
With FS
'Same path as our file
.LookIn = ThisWorkbook.Path
.FileName = "*DataLog.txt"
'Search all files sort by file name
If .Execute(msoSortByFileName, msoSortOrderAscending) = 0 Then
MsgBox "No data files found in " & .LookIn
Exit Sub
End If
'Clear previous data
Set R = Range("A2").CurrentRegion
If R.Row < 2 Then Set R = R.Offset(1)
R.ClearContents
'Show the user that we are working
Application.Cursor = xlWait
DoEvents
For Each ThisFile In .FoundFiles
'Get the date from the file name
ThisDate = Filename2Date(ThisFile)
'Between our dates?
If (ThisDate >= StartDate) And (ThisDate <= EndDate) Then
'Import at the end of the data
Set R = Range("A" & Rows.Count).End(xlUp).Offset(1)
Data = ReadCSV(ThisFile)
R.Resize(UBound(Data) + 1, UBound(Data, 2) + 1) = Data
Count = Count + 1
End If
Next
End With
'Done
Application.Cursor = xlDefault
If Count = 0 Then
MsgBox "No files match your dates"
Else
MsgBox Count & " files imported"
'Hide the form
Me.Hide
End If
End Sub
Private Function Filename2Date(ByVal Fullname As String) As Date
'Convert e.g "C:\20130601142648DataLog.txt" to the date "01.06.2013 14:26:48"
Dim i As Long, j As Long
i = InStrRev(Fullname, "\")
If i > 0 Then Fullname = Mid(Fullname, i + 1)
Fullname = JustNumbers(Fullname)
If Len(Fullname) <> 14 Then Exit Function
Filename2Date = _
DateSerial(Mid(Fullname, 1, 4), Mid(Fullname, 5, 2), Mid(Fullname, 7, 2)) + _
TimeSerial(Mid(Fullname, 9, 2), Mid(Fullname, 11, 2), Mid(Fullname, 13, 2))
End Function
Private Function JustNumbers(ByVal What As String) As String
'Return only numbers from What (by Rick Rothstein)
Dim i As Long, j As Long, Digit As String
For i = 1 To Len(What)
Digit = Mid$(What, i, 1)
If Digit Like "#" Then
j = j + 1
Mid$(What, j, 1) = Digit
End If
Next
JustNumbers = Left$(What, j)
End Function
Private Function ReadCSV(ByVal Fullname As String) As Variant
'Read a CSV file into an array
Const LDelim = vbCrLf 'Line delimiter
Const FDelim = ";" 'Field delimiter
Dim hFile As Integer
Dim Buffer As String
Dim Lines, Line, Data
Dim i As Long, j As Long
'Be sure the file exists
If Dir(Fullname) = "" Then Exit Function
'Open and read all data
hFile = FreeFile
Open Fullname For Binary Access Read As #hFile
Buffer = Space(LOF(hFile))
Get #hFile, , Buffer
Close #hFile
'Split into lines
Lines = Split(Buffer, LDelim)
'Split the first line and prepare the output
'Note: I assume that all lines have the same number of fields
Line = Split(Lines(0), FDelim)
ReDim Data(0 To UBound(Lines), 0 To UBound(Line))
For i = 0 To UBound(Lines)
Line = Split(Lines(i), FDelim)
For j = 0 To UBound(Line)
'Parse the fields
If IsDate(Line(j)) Then
Data(i, j) = CDate(Line(j))
ElseIf IsNumeric(Line(j)) Then
Data(i, j) = CDbl(Line(j))
Else
Data(i, j) = Line(j)
End If
Next
Next
ReadCSV = Data
End Function -
Error while reading file name in a directory
Hi,
I am trying to read all the file names within a directory, however I get the below error while running the code.
Run-time error '5':
Invalid procedure call or argument
The actual path is "Q:\Budget\Historical Budgets\FY15\*.xls*"
and ThisWorkbook.Sheets(1).Range("A1").Value = FY15 in my excel sheet.
"Below is the code I am using"
Dim file As Variant
file = Dir("Q:\Budget\Historical Budgets\" & ThisWorkbook.Sheets(1).Range("A1").Value & "\*.xls*")
If file = "" Then
MsgBox "no files"
Exit Sub
Else
' ... else, count the files
x = 0
Do While file <> ""
x = x + 1
file = Dir
<---- I get the error at this line.
Loop
End If
Could you please help me to solve this problem
Regards, HiteshDo you want to generate a list of all files in a folder, in your spreadsheet? If so, please try this sample code?
Option Explicit
Private cnt As Long
Private arfiles
Private level As Long
Sub Folders()
Dim i As Long
Dim sFolder As String
Dim iStart As Long
Dim iEnd As Long
Dim fOutline As Boolean
arfiles = Array()
cnt = -1
level = 1
sFolder = "C:\Users\Excel\Desktop\Coding\Microsoft Excel\Work Samples\"
ReDim arfiles(2, 0)
If sFolder <> "" Then
SelectFiles sFolder
Application.DisplayAlerts = False
On Error Resume Next
Worksheets("Files").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Worksheets.Add.Name = "Files"
With ActiveSheet
For i = LBound(arfiles, 2) To UBound(arfiles, 2)
If arfiles(0, i) = "" Then
If fOutline Then
Rows(iStart + 1 & ":" & iEnd).Rows.Group
End If
With .Cells(i + 1, arfiles(2, i))
.Value = arfiles(1, i)
.Font.Bold = True
End With
iStart = i + 1
iEnd = iStart
fOutline = False
Else
.Hyperlinks.Add Anchor:=.Cells(i + 1, arfiles(2, i)), _
Address:=arfiles(0, i), _
TextToDisplay:=arfiles(1, i)
iEnd = iEnd + 1
fOutline = True
End If
Next
.Columns("A:Z").ColumnWidth = 5
End With
End If
'just in case there is another set to group
If fOutline Then
Rows(iStart + 1 & ":" & iEnd).Rows.Group
End If
Columns("A:Z").ColumnWidth = 5
ActiveSheet.Outline.ShowLevels RowLevels:=1
ActiveWindow.DisplayGridlines = False
End Sub
Sub SelectFiles(Optional sPath As String)
Static FSO As Object
Dim oSubFolder As Object
Dim oFolder As Object
Dim oFile As Object
Dim oFiles As Object
Dim arPath
If FSO Is Nothing Then
Set FSO = CreateObject("Scripting.FileSystemObject")
End If
If sPath = "" Then
sPath = CurDir
End If
arPath = Split(sPath, "\")
cnt = cnt + 1
ReDim Preserve arfiles(2, cnt)
arfiles(0, cnt) = ""
arfiles(1, cnt) = arPath(level - 1)
arfiles(2, cnt) = level
Set oFolder = FSO.GetFolder(sPath)
Set oFiles = oFolder.Files
For Each oFile In oFiles
cnt = cnt + 1
ReDim Preserve arfiles(2, cnt)
arfiles(0, cnt) = oFolder.Path & "\" & oFile.Name
arfiles(1, cnt) = oFile.Name
arfiles(2, cnt) = level + 1
Next oFile
level = level + 1
For Each oSubFolder In oFolder.Subfolders
SelectFiles oSubFolder.Path
Next
level = level - 1
End Sub
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it. -
How can I extract a file name / path from a local path variable in TestStand?
I have local TestStand string variable, call it 'locals.path', that contains a path to a file including the file name (c:\inputs\input.txt). I need to be able to split up the path (c:\input) and the file name (input.txt) and save them into 2 local variables. What is the best way to do this?
After reading through some of the other forums, it looks like there are some built-in functions that can accomplish this, but I am unable to find how to use them anywhere on the NI web site. One forum said to use the File I/O>Strip Path.file function. How is this called? Is this function in a DLL?
I know that there are a number of DLLs that are installed with TestStand into the c:\windows\system32 directory. One forum made note of CVI_OpenFile / CVI_ReadFIle functions in the cvirt.dll that I used to solve a problem that I had in the past. The problem is that I had no idea that that these functions even existed and would have never known unless a similar question had been posted previously. Is there some place that these DLL function interfaces are defined or documented? Is there a function that can extract the file name out of a string for me?
Thanks,
MikeHi,
There sound like functions in say LabVIEW or CVI.
I have attached a small example which may help. (I have not allowed for any error trapping, if say you dont find the file and cancel)
Regards
Ray Farmer
Message Edited by Ray Farmer on 10-16-2006 10:04 PM
Regards
Ray Farmer
Attachments:
Sequence File1.seq 33 KB -
Hi Friends,
i am using METHOD CL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG
i want to know the file name selected from the path.
example : c:\folder\file.txt.
here i want to know which file i have selected. if it is a small path then we can use SPLIT command but if the path selected is long with special chareters then?
urget requirement.
regards
Kumar M.u can use this function...
CALL FUNCTION 'WS_FILENAME_GET'
EXPORTING
DEF_PATH = 'C:\'
MASK = '*.xls'
MODE = 'O'
TITLE = SY-TITLE
IMPORTING
FILENAME = FILENAME
EXCEPTIONS
INV_WINSYS = 1
NO_BATCH = 2
SELECTION_CANCEL = 3
SELECTION_ERROR = 4
OTHERS = 5.
have a nice day...
Maybe you are looking for
-
Data not displayed for Key Figure of MultiProvider
Hi Folks, I have created a Query on MultiProvider which is actually copied from another Query(based on InfoCube) using RSZC. Now I have the problem with display of data for a KeyFigure in report. No data is displayed for the KeyFigure. The MultiProvi
-
Help finding flexfield please....
Navigate to AR Developer -> setup -> Transactions -> Salespersons Create new Salesperson. On the main screen in the header section, there is a flexfield next to the Transaction Number field. I would like to start using this, but I am having some prob
-
Org.apache.jasper.util.SystemLogHandler@f42160 exception
good afternoon experts, i m developing a project in netbeans 5.5.1 IDE and my backend is microsoft sqlserver, i have developed my project on my laptop, but when i had deploy it on instituion's pc it will cause error "org.apache.jasper.util.SystemLogH
-
How to save 7.0 VI's flat sequences properly as Labview version 6.1
Labview 7.0 has a Save for previous option that allows the vi to be saved as 6.1 vi. In attempt to do that with a VI that has flat sequence, a stacked sequence got added in the VI and a lot of things got screwed up. Is there anything out that that wi
-
Web Services with Large Result Sets
Hi, We have an application where in a call to a web service could potentially yield a large result set. For the sake of argument, lets say that we cannot limit the result set size, i.e., by criteria narrowing or some other means. Have any of you hand