Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Wednesday, March 14, 2012

Adobe Acrobat: Adding JavaScript Addons; Flattening Form Fields

I was using Acrobat 9. I combined some PDFs into one.  One or more of those PDFs was a form, with blanks to be filled out by users.  Thus, my combined PDF also looked like a form.  Specifically, it had a purple banner across the top that read,

Please fill out the following form. If you are a form author, choose Distribute Form in the Forms menu to send it to your recipients.
I wanted to get rid of that banner. One way would have been to print the whole document to PDF, but that would have made it much larger. Among other suggestions, I liked the one pointing to the Flatten Page Content Tool.  It sounded like this would provide what I needed.

To make that tool work, I needed to install a Java script.  The instructions told me that installation simple required me to copy the script into an appropriate folder.  The folder could be Acrobat’s App folder or its User folder, but not both.  The difference was that scripts in the App folder would be available to all users, while scripts in the User folder would be available only to the individual user.
The writer of the instructions said that, on his/her machine, the App folder (which I intended to use) was located at C:\Program Files\Adobe\Acrobat 8.0\Acrobat\JavaScripts.  My system was apparently different from theirs.  The original tipster said that, on her machine, the folder was at C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Javascripts folder.  I suspected (but was not sure) that mine was at C:\Program Files (x86)\Adobe\Acrobat 9.0\Acrobat\Javascripts.

The instructions indicated that there was a way to find the location of the App folder for sure.  I just needed to type “app.getPath("app","javascript");” in the Acrobat JavaScript Console.  The instructions said I could find that by going into Acrobat and hitting Ctrl-J.  But when I did that, I got a JavaScript Debugger that didn’t seem to have any way to do anything with the console.  I could type “app.getPath("app","javascript");” into the open space, but there was no Enter or Run button.  A guide said that, to “evaluate” (presumably meaning “execute”) a single line of Java code, I should put the cursor on that line and press Enter on the numeric keypad or Ctrl-Enter on the regular keyboard.

That worked.  I got “/C/Users/Ray/AppData/Roaming/Adobe/Acrobat/9.0/JavaScripts”.  So apparently my guess was wrong:  this was the folder where I needed to put the Flatten Page Content Tool script.  So I downloaded and unzipped that tool.  From the resulting folder, I moved the PDFScript_FlattenPages.js file to that C:\Users\Ray ... JavaScripts folder.  I had Acrobat running at the time, which was probably completely inappropriate.  I closed it, reopened the offending PDF, right-clicked on its toolbar, and chose More Tools.  There was an apparently new addition:  Add-on Tools Toolbar.  It was already selected.  And now, as I looked more closely at the toolbar, I saw that, indeed, I did have an icon for a hammer hitting  piece of paper – perfect for flattening a document.

The original tipster said this would permanently flatten the fields, but that they could still be edited in Illustrator, Photoshop, etc.  I didn’t care about that; I just wanted to lose the purple banner.  I hit the hammer icon.  It said, “Select Pages to Flatten.”  I chose all.  It was a large document, but the process was almost instantaneous.

About this time, I discovered that I could have just hit the button at the top left to hide that purple banner.  I really knew that already.  I'm sure of it.  Flattening didn’t reduce the PDF size for my purposes either.  OK, futile gesture.

Tuesday, March 13, 2012

Choosing Emacs as a Text Editor with Macro Capabilities

I had a project that called for a text editor with macro capabilities. I went searching for one. This post describes how that turned out.

I started by trying Notepad++. It did have a simple macro recording capability: just select Macro > Start Recording. The particular application I had in mind involved a search for certain text. This couldn't be done in Notepad++. Its help file said, "Currently (v.5.4.3), macros cannot save Find(/Replace) operations."

So I looked for alternatives. Wikipedia offered a longish list of them, but without detailed feature information. I found a Lifehacker article that suggested Emacs as a second-best after Notepad++. I hadn't used Emacs since 1982. Last time I'd tried, maybe around 2005, it had been intimidating. Was I ready to invest time to become competent in Emacs? Lifehacker called it "primarily a text editor for serious programmers." Lifehacker said an alternative with comparably good macro capabilities was Vim or, less intimidatingly, Cream.

I looked at Cream. I saw that it had a keyboard macro capability (Shift-F8 to record, F8 to play). I downloaded and installed it and tried its macro features. It may have saved the macro somewhere, at least temporarily. But it didn't give me an option to save it permanently or assign it to a function key. There didn't seem to be a way to auto-run a macro on startup or file opening. This tool seemed to be rather extremely different from something like Emacs.

What I was really looking for, and what I found at this point, was the Extra Features table in Wikipedia's comparison of text editors. There, I found a column, "Macro Language." I didn't necessarily need a whole language, but I had missed not having something along those lines, which I had used extensively in certain DOS programs (especially WordPerfect and Paradox) in the 1990s, and had never gotten back to after switching to Microsoft Office. If I relied on Wikipedia's comparison to steer me to a text editor that definitely had a macro language, newline conversion capability, large file support, and graphical shell integration, for no cost in a Windows environment, then my candidates seemed to be AkelPad, ConTEXT, GNU Emacs, PSPad, Vim, and XEmacs.

I had missed some things about the Emacs world, and was inclined in that direction. Wikipedia and WikiVs articles on the choice between Emacs and Vim did not change that feeling. After browsing a discussion or two of the choice between GNU Emacs and XEmacs, I decided I preferred the former. But then it developed that there were quite a few other versions of Emacs. I was tempted to go with MicroEmacs, as I thought it might be simpler. The JASSPA version seemed to be most actively developed.  But then I decided that, to avoid bugs and have deep support in complex problems, it made more sense to go with the most mainstream version, and that seemed to be GNU Emacs.

I downloaded and installed the most recent GNU Emacs from Softpedia (apparently released within the past few months), though possibly I should have gone to the official download site. I say "installed," but actually it seemed to be pretty much a portable. Looking through the two accompanying "read-me" files (one of which was not formatted for use on Windows machines), I saw that they advised putting it into a folder whose directory path contained no spaces. There were a few installation options. One was to run the file called Emacs\bin\addpm.exe. Another was to create a shortcut to Emacs\bin\runemacs.exe. There was also the option of running a REG file to make some changes. The file as they gave it to me contained just a couple of lines that added a context menu option, "Open with Emacs." The entire contents of the REG file were:

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\AllFilesystemObjects\shell\Open With Emacs\command]
@="C:\\emacs\\bin\\emacsclientw.exe -n -a \"C:\\emacs\\bin\\runemacs.exe\" \"%1\""
The read-me seemed to say that I could add some formatting options to that REG file, specifically:
[HKEY_LOCAL_MACHINE\SOFTWARE\GNU\Emacs]
"Emacs.Background"="Black"
"Emacs.Foreground"="Wheat"
"Emacs.ScrollBars"="OFF"
"Emacs.MenuBar"="OFF"
"Emacs.ToolBar"="OFF"
"Emacs.Geometry"="125x43+0+0"
But when I tried to add those keys and values to the registry manually, I didn't see that they were making any difference. I wondered if they were perhaps intended for the text version as distinct from the GUI version; the latter seemed to have its own menu-driven configuration options.

That seemed to be all there was, by way of preliminaries. Going into the actual Emacs program, the read-me files recommended starting with Emacs > Help > Tutorial. The opening screen contained a link to the tutorial and also to a Guided Tour and to the Emacs Manual. The tutorial was contained within Emacs and didn't seem to be available online. The Guided Tour and the Emacs Manual were available online. There were also other tutorials out there. Examples included a Rice University PDF that only seemed to be available from a University of Illinois website, a University of Chicago tutorial, and a GNU Emacs 101 for Beginners webpage. There were other help sources as well, including the GNU Emacs FAQ for MS Windows, the help-emacs-windows listserv, and two Usenet groups (gnu.emacs.help and comp.emacs).

The GNU Emacs for Beginners page, and others, had some tips. One was to start with the menus and worry about the "keybindings" (i.e., the Ctrl- and Alt- multi-key options) later. Another was to use Ctrl-] (i.e., control - right bracket) to kill funky processes, if the program started to seem out of control. Also, they said, "Meta" was the old (still used in Emacs) name for the Alt key.

The University of Chicago tutorial seemed to have been written for non-GUI users. I read it partway nonetheless. It was talking about key combinations. It said they were written in shorthand, as C- (for Ctrl-) and M- (for Meta- (i.e., Alt-)). Sometimes it would apparently be necessary to use Esc instead of Alt, but in those cases (unlike C- and M-) you'd just tap it, not hold it. You'd do your work in a buffer, not directly in a file; the changes in the buffer would then be written to the file. C-x commands would do things on the environmental level (e.g., open files, save your work, manipulate windows). Control combinations had to be entered sequentially, lifting off the Ctrl key and then hitting it again as needed.  For example, C-x C-e did not mean C-x-e.  The Rice University thing (dated 2002) also had information about these key combinations.

It looked like the best sources of information would be the FAQs, the Emacs Manual, and the Guided Tour, which was actually more like an introduction to general concepts.  The manual included in Emacs itself seemed to be the same as the online manual.  The included tutorial was actually just a long (maybe 15-page) single-spaced text file.

I wasn't sure I needed all that right now.  I went looking for information on macros specifically.  So that started my education in Emacs:  Ctrl-F (or should I say C-f) would not do a Find; instead, it would move the cursor Forward one space.  To find the part of the tutorial that talked about macros, I needed to use C-s (i..e, search forward) or perhaps C-r (i.e., reverse).  There wasn't a search box per se; there was a search line on the bottom of the screen.  Nothing on macros in the tutorial.  The online Guided Tour said F3 would start recording a macro and F4 would stop and would also do playback.

So, OK, I would open a file of the kind that I wanted to edit; I would go to its end, since I was looking for the last occurrence of a certain text string (specifically, "Content-Disposition: attachment;"); I would do a C-r to back up to that last occurrence; and then I would need to know how to delete everything after that point.  So here were the steps to get that far:
  • Opening the file:  Menu > File > Open
  • Going to its end:  C-end (just like in Word)
  • Searching for last occurrence of text:  C-r.
  • Text to search for:  I could have typed in the "Content-Disposition: attachment;" string that I was searching for, but could I paste it into the search?  Ctrl-V didn't work, at least not without customization.  A search led to an indication that the customization itself could be relatively easy, though there were multiple preparatory steps.  First, I had to have an "init" file.  It could be called _emacs and it had to be in my Home directory.  To find Home, I typed C-x C-e (insert (getenv "HOME")) and saw that it printed, in the text of the file I was looking at, this location:  C:\Users\Ray\AppData\Roaming.  (I had to give it a minute after the C-e before it brought up the "Eval" space at the bottom of the screen.  Once it did that, I could type the (insert (getenv "HOME")) part.)  In Windows Explorer, I created a new _emacs file (not _emacs.txt) in that folder, opened it with Notepad, put (setq x-select-enable-clipboard t) into it, and closed it.  I closed and restarted Emacs.  Ctrl-V still did not work to paste contents of the Windows clipboard into Emacs.  I noticed this in the lower half of the Emacs screen: Warning (initialization): `_emacs' init file is deprecated, please use `.emacs'. I tried to change _emacs to .emacs, but Windows Explorer said, "You must type a valid file name."  So I left it as _emacs and, ultimately, I just typed in the "Content-Disposition: attachment;" text that I was looking for.
  • Marking the start of the text to be deleted:  I wanted to delete everything from "Content-Disposition: attachment;" on to the end of the file.  In Emacs-speak, this was called "killing" a "region."  First, I had to set the "mark" at one end of the region.  I probably could have done that already at the end of the file, but I wasn't thinking that way.  I was at "Content-Disposition: attachment;" now, so I set the mark by hitting C-space.  The bottom line in Emacs gave me a gratifying little confirmation:  "Mark set."
  • Marking the end of the text to be deleted:  the deletion would apply to everything between "mark" and "point."  Point seemed to mean just the location of the cursor.  So I just hit Ctrl-End to go to the end of the file.  I saw that all this text was now highlighted.
  • Deleting the selected text:  to kill the region, I just hit Delete.
  • Saving and closing the file:  Menu > File > Close.  I got a dialog telling me that a buffer had been modified and asking if I wanted to kill anyway.  I said yes, and then I reopened the file to see what happened.  My change had not been saved, so I redid it, and this time I did save first.  I used the key commands instead of the menu pick:  C-x C-s.  Then I quit with C-x C-c.
Now I wanted to be able to automate those commands in a macro.  That called for another sequence of steps:
  • Create the macro:  I opened the next file that needed the treatment just described.  I hit F3 and went through those steps, ending with the file save.  Then I hit F4 to end the definition.  I got a confirmation at the bottom:  "Keyboard macro defined."
  • Name the macro:  I just wanted to call it Macro1.  It seemed that several macro-related commands started with C-x C-k.  To name the macro, I typed C-x C-k n Macro1 followed by Enter.  It didn't give me a confirmation, or maybe I missed it before I hit Enter, which may have been unnecessary.
  • Bind the macro to a specified key:  in case I wanted to be able to run Macro1 by just hitting a key (instead of using its name), I typed C-x C-k b 1.  This command would "b"ind the last keyboard macro (i.e., the one I had just defined) to key 1.  To run it, I could hit C-x C-k 1.  The same approach would work if I wanted to assign macros to C-x C-k 2 through 9 and A through Z (capital letters only).  That is, (a) the binding process would be this simple, for 1-9 and A-Z, and (b) those particular key combinations were safe to use (i.e., were not already spoken for).  I got a confirmation:  "Keyboard macro bound to C_x C-k 1."
  • Save the macro in a file:  to make Macro1 available if I stopped and restarted Emacs, I had to "visit" the file where I wanted to save its definition.  I decided to call this file "Macros."  There was a menu option to visit a new file.  I tried C-x C-f Macros [Enter].  It defaulted to putting this file in the directory where I had last been working (i.e., where the files I was editing were located).  I decided this was OK for now; I could move the Macros file later if I wanted to keep it after this job was done.  It confirmed:  New file.  Now, to save Macro1 in Macros, I typed M-x insert-kbd-macro [Enter] Macro1 [Enter], where M- meant Alt-.  The top pane showed a bunch of mostly numbers.
  • Test the macro:  I closed Emacs.  The confirmation line asked if I wanted to save Macros.  I typed y.  It closed.  I reopened Emacs and typed C-x C-k 1.  The bottom line said, "C-x C-k 1 is undefined."  I typed M-x load-file [Enter].  It volunteered to load something from my Emacs program folder.  That wasn't where I had saved the Macros file.  So I would apparently have to type the full path name.  Once I did type D:\Folder\Subfolder\Subsubfolder\Macros, I got a confirmation:  Loading ... done.  I made sure the next file to be fixed was visible and that's where the cursor was, and then I tried C-x C-k 1 again. Still undefined.  I tried F4:  "No kbd macro has been defined."  It wouldn't accept C-x C-k e Macro1.  I moved the file to D:\Folder and renamed it to Macros.el.  This made no difference.
  • Correct my mistakes:  eventually I came to understand that I should have named the macro (C-x C-k n Macro1) and then saved it by opening C:\Users\Ray\AppData\Roaming\_emacs and then typing M-x insert-kbd-macro [Enter] Macro1 [Enter].  So I hit F3, re-ran the sequence of steps, hit F4, and then named and saved it in that way.  Or, I should say, tried to save.  When I typed M-x insert-kbd-macro [Enter], it prompted me with "Insert kbd macro (name)," and when I typed Macro1, it said, "No match."  I opened another file to edit, hit F4, and it ran.  But it ended in the _emacs file, so maybe I hadn't hit F4 to end it at the right time.  I went through the F3 paces and so forth, another time, with another file.  This time it seemed to work:  the _emacs file in the bottom pane of the two-pane Emacs window now contained some codes.  I saved _emacs.  But, oops, I hadn't assigned it to a key.  I opened another file to edit, hit F4, and observed that the macro failed to run.  I must have screwed something up.  I went through the F3 process again.  This time I hit F4 several times at the end.  I typed C-x C-k n Macro1a [Enter].  I bound it to the 1 key by typing C-x C-k b 1.  I saved it to _emacs by clicking in the bottom pane, where _emacs was still open, and typing M-x insert-kbd-macro [Enter] Macro1a [Enter].  This added more text to _emacs, identical to what I had added before except it referred to Macro1a instead of Macro1.  I manually deleted the extraneous Macro1a lines and saved _emacs.  I opened another file to edit and hit C-x C-k 1.  The macro didn't work.  It went to the end of the file and stopped.  I suspected the reason was that, at file's end, I had hit C-f (i.e., the Windows Find combination), intending to tell it to search backwards, and had gotten an error message:  I was supposed to search with C-r from the file's end (not with C-f).  Apparently the error message terminated macro recording.  So I went through the steps again, starting with F3.  This time, there was a larger amount of code saved in _emacs, in the bottom pane, and it included references to desired steps like "delete) and "(menu-bar) file save-buffer."  I manually edited _emacs again so that Macro1 (not Macro1a) would be associated with all these nice lush codes.  I opened another file and hit C-x C-k 1.  This time, it got to approximately the point where it should have started deleting, and stopped there with an error on the bottom line:  "After 0 kbd macro iterations: Keyboard macro terminated by a command ringing the bell."  I suspected this, too, was due to an error during macro recording, though not one that I would have expected to matter.  After hitting C-r, I had told Emacs to search backwards for Content-d.  That's as far as I got:  a small d, instead of D as in Disposition.  Typo.  But the macro had recorded it literally, which it would not have done when recording a keyboard macro in Word.  I wondered if I could please make it through a F3 macro recording session without any typographical errors.  Trying again with F3, I got another Macro1a saved in _emacs.  And this time, by God, it worked.  C-x C-k 1 did exactly what it was supposed to do, right down to the final step of saving the edited file.
That worked.  I had a text editor with macro capabilities.  And I could tell already that it was going to be sweet, special, loving, but also nasty, and sweaty, and sometimes hostile and ugly . . . oops, familiar rant, wrong context.  Point is, I was coming home.

Thursday, March 1, 2012

Using Excel to Clean Unwanted Characters from Filenames or Other Text

I was trying to organize some files.  This post contains some notes I made on ways of using Microsoft Excel to change a list of filenames.  The renaming project drew on file renaming techniques described elsewhere.

In various attempts in this process, I came up against situations where inconsistent punctuation and other filename characteristics made the process unnecessarily complicated.  For instance, file names might refer to "Barack Obama," "Barack H. Obama," "President Obama," and so forth.  These would all be alphabetized differently.  Duplicates might be concealed, and files that belonged together topically might be overlooked.

In part, that was an issue of choosing and using consistent file naming conventions.  But at this point, given that the files were already named, there was an issue of how to deal with punctuation and other non-alphanumeric characters.  I wondered if there was a relatively straightforward way to get my arms around the varieties of character usage within a particular corpus.

The first task seemed to be identifying what unwanted characters were in use. Taking Microsoft Excel as my weapon du jour, I made a list of the filenames that I might want to change, using DIR on the Windows command line (see the comments following another recent post). I pasted that list of filenames into Excel.

Next, I ran a search and found several ingenious approaches to related problems. One would use a wildcard search-and-replace in Microsoft Word:   search for ? (making sure to indicate that this would be a "Use wildcards" search) and replace with ^&^p to put the same character (that is, any character) on a line by itself; then paste the whole text into Excel and do a unique filter to get all of the unique characters found in the text. This did not seem likely to work for my purposes, unfortunately. For one thing, Excel 2003 was limited to 65,536 rows, and there could easily be more characters than that in a text being analyzed.  I had also found that spreadsheets capable of handling more rows could be slow at it.

There were other approaches that used an array formula or a script. I was not as comfortable with those that I did not understand, because it would be difficult for me to work through their logic and make sure they were really doing what I wanted them to do. An unnoticed mistake could have unfortunate effects when altering a large or important text, or when renaming thousands of files.

Another possibility came to mind as I looked at the suggestion to use MoreFunc's REGEX.COUNT function (alternately, Excel's SUBSTITUTE or possibly MATCH) to produce character-by-character counts.  I ran a search and found some interesting variations in SUBSTITUTE, including nested and case-insensitive substitutions, along with the CLEAN function. One solution, it seemed, would be to use 26 columns containing something like =SUBSTITUTE(UPPER(A1),"","") to replace all upper- and lower-case letters with nothing, another 10 columns to do the same for numbers, and then see what's left.

With SUBSTITUTE, one possibility was to set up a map. Put the rows of text being analyzed in one worksheet ("Sheet1"). Create a second worksheet ("Sheet2") within the same Excel file.  In Sheet2, make each row relate to the row of the same number in Sheet1. So, for example, if there was a text string in cell A5 in Sheet1, there would be a row of characters across row 5 in Sheet2. Each cell in that row would count the occurrences of a specific character. For example, the 65th column would detect occurrences of the character whose Excel code happened to be 65 (that is, the letter "A," producible by =CHAR(65)).  The chief problem with this approach was that its calculations would take a year.  It would also max out Excel 2003's limit of 256 columns.  It would have the advantage of transparency:  I would be able to see much of what was happening in the data.

I found a user-defined function (UDF) -- what I had been referring to as a script -- called SUBSTITUTELIST.  This UDF would let me indicate a list of characters to simply remove.  In naming files, I would definitely not want to include many of the odd characters that were readily visible if, say, I opened a non-text file in Notepad.



The first step, with SUBSTITUTELIST, was to define it as a function that I could use in spreadsheet formulas.  To do that, using the steps described atop another post, I copied and pasted this text into an Excel module:

Function SubstituteList(rString As String, rList As Range) As String
Dim rCell As Range
For Each rCell In rList
rString = Replace(rString, rCell.Text, "")
Next rCell
SubstituteList = rString
End Function
I didn't write that code, and was only partly clear on what it said.  It appeared, though, that its middle line was going to replace rString with nothing (""). In other words, rString was being removed. Now I had to tell it what characters to treat as rString. In the spreadsheet listing the filenames I wanted to work on, I opened a new worksheet, called Sheet2, and put the numbers 1 through 255 in cells A2 to A256. (Two easy ways to insert a series of numbers: use =A1+1 in cell A2, and so forth; or enter the first two numbers (i.e., 1 and 2) manually, highlight the cells to be filled, and then use Edit > Insert > Series. The Alt command option would probably still work in post-2003 versions of Excel: Alt-E, I, S, Enter.)
Then, in Sheet2 cell B1, I typed =CHAR(A1), and copied it down to B255. So now column B contained the actual characters I wanted to look at, whose CHAR equivalents were shown in column A. Finally, column C contained the characters to be removed from consideration.  For example, in cell C128, I typed =B128.  That put a copy of CHAR(127) into column C.  SUBSTITUTELIST was going to remove anything in column C.  So that particular character would be removed from the cell in Sheet1 where I was going to be using SUBSTITUTELIST.  Depending on the situation, I might or might not want to remove all non-alphanumeric characters.  For instance, I thought that what I would really want to do with something like the euro character (€), in a filename, would not be to eliminate it, but rather to replace it (e.g., €35 becomes EUR 35).

To use SUBSTITUTELIST, I put my text to be analyzed in column A of Sheet1. In B1, I entered this: =SUBSTITUTELIST(A1,Sheet2!$C$1:$C$255). I copied that formula all the way down, next to each text string to be examined. That gave me a collection of funky characters in Sheet1 column B. Originally, I added TRIM to the SUBSTITUTELIST formula just cited, but then I realized that I actually wanted to see the pattern of spaces and other non-alphanumeric characters.

SUBSTITUTELIST seemed to have potential for single-character eliminations, but it didn't seem capable of substitutions involving multiple-character strings (e.g., EUR in place of €).  It looked like a relatively simple change to SUBSTITUTELIST might do the job, but I had little ability for that sort of work at this point, so I posted a question on it.  One reply to that question suggested a UDF called CLEANUPTEXT.  The contents of that UDF (created in the same manner as SUBSTITUTELIST, above) were as follows:

Option Explicit
Sub cleanupText()

Dim allTxt() As Variant, sublist() As Variant
Dim i As Long, j As Long, k As Long, tdots As Integer

'Store data from sheets in arrays.
allTxt = Sheets(1).UsedRange.Value
sublist = Sheets(2).UsedRange.Offset(1, 0).Resize(Sheets(2).UsedRange.Rows.Count - 1, Sheets(2).UsedRange.Columns.Count).Value

For i = 1 To UBound(allTxt, 1)
    For j = 1 To UBound(allTxt, 2)
        'Loop through replacement terms and make replacements to data in array.
        For k = 1 To UBound(sublist, 1)
            allTxt(i, j) = Replace(allTxt(i, j), sublist(k, 1), sublist(k, 2))
        Next k
        allTxt(i, j) = Trim(allTxt(i, j))
       
'Remove series of trailing periods.
        If Right(allTxt(i, j), 1) = "." Then
            tdots = 1
        Else
            tdots = 0
        End If
        Do While tdots = 1
            allTxt(i, j) = Left(allTxt(i, j), Len(allTxt(i, j)) - 1)
            If Right(allTxt(i, j), 1) = "." Then
                tdots = 1
            Else
                tdots = 0
            End If
        Loop
        
allTxt(i, j) = Trim(allTxt(i, j))
    Next j
Next i
'Print cleaned up results in array onto sheet.
ActiveSheet.UsedRange.Value = allTxt
End Sub


The instructions accompanying that UDF seemed to indicate that it required a separate worksheet, called Sheet2, containing the "before" terms in column A of Sheet2, and the "after" terms in column B of that sheet; and Sheet1 had to be the name of the tab containg the text being operated on.  In response to my question, the text shown in blue (above) was designed to remove trailing dots from the text being modified.  I did not actually try this UDF, but I hoped that I would not have to write similar lines of text for other kinds of unwanted text strings -- that, in other words, the column A / column B replacement approach would suffice.  If so, I might try to simplify this UDF by removing the lines in blue.

On a separate note, I had noticed that some of the files in my list looked like their names were identical except for punctuation, so I added a column, in my spreadsheet that listed filenames, for this formula:  =LOWER(substitutelist(M2,Sheet2!$C$1:$C$255)).  M2 contained the existing filename, or part thereof, and Sheet2 column C was set to eliminate all non-alphanumeric characters, as shown above.  This step did succeed in highlighting some duplicate filenames and other issues.

Another problem was that, in some cases, I would have to rename files before proceeding with something like SUBSTITUTELIST.  The specific problem was that some characters in filenames would defeat batch commands.  That is, I could have a command to change a filename, perhaps in response to an insight emerging from SUBSTITUTELIST; but the command might not run.  So I would have to change or delete those troublesome characters first.  (I often used Excel formulas to generate commands that I could run in a batch file to rename numerous files.  The basic idea here was that I would put the existing filename in cell A1 of an empty worksheet, and the desired filename in cell B1, and then I would enter this formula in cell C1:  ="ren "&CHAR(34)&A2&CHAR(34)&" "&B2. (If the new filename in B2 had spaces in it, then it too would have to be surrounded by CHAR(34) instances, as done in that formula for cell A1.)  The particular chacters at issue here were percent symbols and possibly exclamation marks.  The commands were right.  They would run if I typed them into the command line, or copied and pasted them there.  But they wouldn't work from within a batch file.  To address this concern, I just deleted the exclamation marks, and I replaced the percent symbols with "pct" (e.g., 45% became 45pct).

In some cases, I would want a tool that could replace one or more undesirable characters, in a single bulk process, with one or more preferred characters.  In part, this was a simple interest in transliteration or Romanization (i.e., converting foreign-language characters to the standard English alphabet). There would be at least two reasons to do that. One was that I had run into some file handling issues with some such characters. I recalled one recent case where something that looked like a C (maybe ḉ or ć or ĉ or ċ or č) was not working correctly with some backup program or something. The other reason was that I might not remember which character to use when doing filename searches.  So, for instance, if I was looking for all of the files containing a copy of someone's resume, I might or might not want to have to search for both "resume" and "résumé."  There were many Romanization tables for various languages, possibly best approached by finding conversion tables for the thousands of possible Unicode characters.  This could take further attention, as there were multiple kinds of Unicode, not all of which might be consistent with Excel's coding.  In filenames, especially, examples involving several characters could include "pct" (above) and the replacement of $ with USD and of © with (C).  One readability example, arising where HTML has become involved, would be to replace the HTML code of ' with the apostrophe.

As I thought further about the problem, I realized that characters might be unwanted in context, not in isolation. For instance, the hyphen ("-") could be fine in some settings, not fine in others. At the risk of opening the door to complexity, it seemed the ideal approach (perhaps the less messy approach, in the long run) would give me the possibility of listing multi-character combinations and indicating their desired replacement. I found a UDF called SUPERSUB that seemed to be just what the doctor ordered:

Function SuperSub(OriginalText As String, rngOldText As Range)
    Dim cel As Range
    Dim strOldText As String, strNewText As String
     'loop through list of old_text used in substitute
    For Each cel In rngOldText.Cells
        strOldText = cel.Value
        strNewText = cel.Offset(0, 1).Value
        OriginalText = Application.WorksheetFunction.Substitute(OriginalText, strOldText, strNewText)
    Next cel
    SuperSub = OriginalText
End Function


But, again, I did not try this script at the time, but was merely preserving its information here for possible future application.

Another post offered a UDF called REMOVEPUNCTUATION where I could create a list of items to replace, and their replacements, within the macro.  The text of that one (with a few illustrative examples) was as follows:

Sub test()
Dim c As Range, t As String
For Each c In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
    t = UCase(" " & RemovePunctuation(c.Text) & " ")
    t = Replace(t, " AVE ", " AVENUE ")
    t = Replace(t, " BLVD ", " BOULEVARD ")
    t = Replace(t, " BVD ", " BOULEVARD ")
    t = Replace(t, " CYN ", " CANYON ")
    t = Replace(t, " CTR ", " CENTER ")
    t = Replace(t, " CIR ", " CIRCLE ")
    t = Replace(t, " CT ", " COURT ")
    t = Replace(t, " DR ", " DRIVE ")
    t = Replace(t, " FWY ", " FREEWAY ")
    t = Replace(t, " HBR ", " HARBOR ")
    t = Replace(t, " HTS ", " HEIGHTS ")
    t = Replace(t, " HWY ", " HIGHWAY ")
    t = Replace(t, " JCT ", " JUNCTION ")
    t = Replace(t, " LN ", " LANE ")
    t = Replace(t, " MTN ", " MOUNTAIN ")
    t = Replace(t, " PKWY ", " PARKWAY ")
    t = Replace(t, " PL ", " PLACE ")
    t = Replace(t, " PLZ ", " PLAZA ")
    t = Replace(t, " RDG ", " RIDGE ")
    t = Replace(t, " RD ", " ROAD ")
    t = Replace(t, " RTE ", " ROUTE ")
    t = Replace(t, " ST ", " STREET ")
    t = Replace(t, " TRWY ", " THROUGHWAY ")
    t = Replace(t, " TL ", " TRAIL ")
    t = Replace(t, " TPKE ", " TURNPIKE ")
    t = Replace(t, " VLY ", " VALLEY ")
    t = Replace(t, " VLG ", " VILLAGE ")
    t = Replace(t, " APT ", " APARTMENT ")
    t = Replace(t, " APTS ", " APARTMENTS ")
    t = Replace(t, " BLDG ", " BUILDING ")
    t = Replace(t, " FLR ", " FLOOR ")
    t = Replace(t, " OFC ", " OFFICE ")
    t = Replace(t, " OF ", " OFFICE ")
    t = Replace(t, " APT ", " APARTMENT ")
    t = Replace(t, " STE ", " SUITE ")
    t = Replace(t, " N ", " NORTH ")
    t = Replace(t, " E ", " EAST ")
    t = Replace(t, " S ", " SOUTH ")
    t = Replace(t, " W ", " WEST ")
    t = Replace(t, " NE ", " NORTHEAST ")
    t = Replace(t, " SE ", " SOUTHEAST ")
    t = Replace(t, " SW ", " SOUTHWEST ")
    t = Replace(t, " NW ", " NORTHWEST ")
    c = Trim(t)
Next
End Sub


Function RemovePunctuation(r As String) As String
With CreateObject("vbscript.regexp")
    .Pattern = "[^A-Z0-9 ]"
    .IgnoreCase = True
    .Global = True
    RemovePunctuation = .Replace(r, "")
End With
End Function


It seemed that, if I used REMOVEPUNCTUATION to make a large number of changes (more than just the few dozen shown here), I might use Excel to generate the text of the additional lines to be inserted into the REMOVEPUNCTUATION script.

That was the extent of these notes.  I would have to await another situation requiring mass file renaming in order to test these techniques.

Saturday, January 14, 2012

Combining PDFs with PDFsam: Introductory Syntax

I was using Windows 7.  I had a project that would benefit from automated merging of multiple PDFs into a single PDF.  It looked like PDFsam would be useful for this purpose.

PDFsam had GUI and Console options.  In other words, it could be accessed through a user-friendly interface, like most Windows programs, and it could also be used on the command line.  My project had certain complexities, such that the GUI approach would not be ideal.  This post describes the steps I took to learn how to use the Console.

I began with the Console section of the PDFsam wiki.  It led to a page providing information on console parameters and commands.  The explanation was too thin, so I did a search for more guidance. This led to a 33-page Tutorial (installed with the program files). It also led to a thread that reminded me not to forget the PDFsam Forums.

The Tutorial (p. 18) seemed to say that, in PDFsam-speak, what I wanted to do was to Merge files, and for this I would use the Concat option. Other options, not of interest here, included Split and Encrypt. It appeared that PDFsam syntax would call for very long commands. Looking for examples, I went to a forum thread, but that pointed me back toward the wiki page (above).

The Tutorial said that, to make PDFsam run from the command line (i.e., Console), I could either type a certain command or just use one of the scripts in the bin folder where the program was installed (e.g., C:\Program Files\pdfsam\bin).  In that bin folder, it appeared I had my pick from two scripts, provided in Linux (.sh) and Windows batch (.bat) versions.  Since I wanted the Console, not the GUI, I focused on run-console.bat.  Its contents seemed to address various details that I didn't clearly understand, and didn't necessarily want to study; it just looked like the thing I would need to use.  So I created a shortcut to it and put that in my Start Menu. I also edited the Tutorial, adding bookmarks to the various sections, and moved it to the Start Menu too.  (My customized Start Menu would survive any subsequent Windows reinstallation, so I probably wouldn't need to do this housekeeping again, if I had to install PDFsam in a new Windows installation sometime down the line.)

Unfortunately, the run-console.bat batch file didn't work for me.  It gave me an endlessly scrolling set of messages. They were ripping past too quickly to read.  I hit PrintScreen, opened IrfanView (any image editor would do, as would Microsoft Word or Wordpad), and pasted the screenshot (Ctrl-V).  (I could have just hit Ctrl-C, or possibly the Pause key.)  Now I could see that it was just the same error message, repeating over and over:

java is not recognized as an internal or external command, operable program or batch file
Why wasn't my system recognizing java?  I right-clicked on run-console.bat, chose Edit, and looked for the line that referred to java. I couldn't quite figure out where the problem was, so I stuck in a "pause" command somewhere, saved the batch file, and, this time, ran it from the command line instead of from the shortcut. That way, the error statements would stay onscreen instead of scrolling past too quickly or disappearing when the batch file finished running. (This was another instance where it was handy to have the right-click option, "Open command window here," provided by Ultimate Windows Tweaker.)

Running the batch command meant just typing its name and hitting Enter. It paused where I had put the pause command, without any obvious errors, so I moved the pause command further down, saved, and repeated the cycle. (Running run-console.bat again required just hitting the Up key to repeat the command.) That's where the problem was: now I had the endless scrolling again. I hit Ctrl-C a couple of times to abort the batch file.

I played around with the batch file for a while, and eventually realized that maybe the problem was that the JAVA_HOME variable had not yet been assigned a value on my system. It appeared that the batch file was supposed to tell me this; if so, it wasn't working right. I went into Start > Run > SystemPropertiesAdvanced.exe > Environment Variables and, sure enough, no JAVA_HOME variable. I had already installed the Java Runtime Environment, and I almost always used the default installation paths when installing programs, so the advice seemed to be that the JAVA_HOME variable should point to C:\Program Files\Java\jre6. Since this folder name ("Program Files") had a space in it, apparently I would need to use the shortened, DOS-style name for it -- known as an "8.3" filename because it would have eight characters before the dot and three afterwards (e.g., yourfile.txt).

I knew the shortened name of that folder would probably contain Progra~1 (instead of "Program Files"), and I could have just experimented with that, but I had seen instances where it would be Progra~2 or something else, and anyway I wanted to know how to get the 8.3 name. Microsoft advised using the GetShortPathName function to figure it out, but that seemed to involve programming, and programming is a lot of work. Instead, I ran a search that took me to ShortPath by Marcello Zaniboni. To get ShortPath to work from the command line, I tried the C:\Windows shortcut trick, but it didn't work. I didn't want to add ShortPath to my PATH yet, so I just opened a command window in the folder where ShortPath.exe was located, typed "ShortPath " (with an ending space) but didn't hit Enter, and then dragged the C:\Program Files\Java\jre6 folder into that command window from Windows Explorer. (I think this worked because I had installed DropCommand. Otherwise I might have had to type it out, with quotation marks.)

ShortPath told me that, actually, the short path to that folder was C:\PROGRA~2\JAVA\JRE6. So I went back into SystemPropertiesAdvanced.exe > Environment Variables > System Variables > New > Variable Name = JAVA_HOME, Variable Value = C:\PROGRA~2\JAVA\JRE6. I OKed out of there and rebooted.

After doing that, I still had to play with the batch file for a long time, in a quest to learn, remember, get lucky, or otherwise do what I needed to make it work. By the time I was done, I almost thought that I would have been further ahead just using the command given in the wiki:
java -Dlog4j.configuration=console-log4j.xml -jar pdfsam-console-2.1.1e.jar
except that that didn't work either because, as I soon realized, it was a Linux command. I also did not fare too well with the advice to type "run-console.bat -h concat" for information on the syntax for the Concat option, because the run-console.bat file itself was not yet working.

The Tutorial (pp. 19-20) said that I had three ways to indicate which files I wanted to merge. Instead of entering one parameter to indicate a directory and then entering another parameter to indicate one or more files in that directory, it seemed I would want the option that would allow me to specify a file (including its path) on a single line. Evidently I could list a number of PDF files in a separate XML file, and invoke that file (with its list of PDFs) by using the -l (that's an L, not a one) option. But it wasn't working right. Ultimately, I posted a question on it. Andrea (a guy from the Netherlands), creator of PDFsam, posted a reply within 36 hours. And that got me where I needed to go. I was able to get a test run to work, with a run-console.bat file whose contents (viewed in something like Notepad, of course, not in a word processor like Word that would add all kinds of invisible junk) were as follows:
@echo off

set JAVA=%JAVA_HOME%\BIN\JAVA

set JAVA_OPTS=-Xmx256m -Dlog4j.configuration=console-log4j.xml

set CONSOLE_JAR="C:\Program Files (x86)\pdfsam\lib\pdfsam-console-
2.3.1e.jar"

@echo on

%JAVA% %JAVA_OPTS% -jar %CONSOLE_JAR% -l D:\Current\ConcatList.xml -o
D:\Current\PDFsamOut\Merged.pdf concat
While I wasn't entirely clear on what all those lines did, the basic idea seemed to be that the first lines would define JAVA, JAVA_OPTS, and CONSOLE_JAR, and then the last line would combine them all into one big command. That command seemed to say, "Run Java with these options, using this jar file for specific instructions; take your input from the PDF files listed in ConcatList.xml; and output a single PDF file, Merged.pdf, containing all of those PDF files." To make that work, I needed to know the format of the ConcatList.xml file. Here's the one that worked for me in this test run:
<?xml version="1.0" encoding="UTF-8"?>
<filelist>
<file value="D:\Current\TestDir1\x1.pdf"/>
<file value="D:\Current\TestDir2\x2.pdf"/>
</filelist>
I just needed a File Value line for each PDF to be merged, using the syntax shown.  To summarize, then, I used Notepad to create two files.  One, called run-console.bat, contained the first half-dozen lines of code shown above, beginning with @echo off.  The other, ConcatList.xml, contained these last five lines of code, beginning with the "xml version" line.  ConcatList.xml would contain File Value lines, each designating a PDF to be merged into the larger output PDF (and there were other options for ConcatList.xml; I just didn't need them for my project), and run-concat.bat would read those lines and do the actual concatenation into a single output PDF.

Wednesday, December 30, 2009

Sorting and Manipulating a Long Text List to Eliminate Some Files

In Windows XP, I made a listing of all of the files on a hard drive.  For that, I could have typed DIR *.* > OUTPUTFILE.TXT, but instead I used PrintFolders.  I selected the option for full pathnames, so each line in the file list was like this:  D:\FOLDER\SUBFOLDER\FILENAME.EXT, along with date and file size information.

I wanted to sort the lines in this file list alphabetically.  They already were sorted that way, but DIR and PrintFolders tended to insert blank lines and other lines (e.g., "=======" divider lines) that I didn't want in my final list.  The question was, how could I do that sort?  I tried the SORT command built into WinXP, but it seemed my list was too long.  I tried importing OUTPUTFILE.TXT into Excel, but it had more than 65,536 lines, so Excel couldn't handle it.  It gave me a "File not loaded completely" message.  I tried importing it into Microsoft Access, but it ended with this:

Import Text Wizard

Finished importing file 'D:\FOLDER\SUBFOLDER\OUTPUTFILE.TXT to table 'OUTPUTTXT'.  Not all of your data was successfully imported.  Error descriptions with associated row numbers of bad records can be found in the Microsoft Office Access table 'OUTPUTFILE.TXT'.

And then it turned out that it hadn't actually imported anything.  At this point, I didn't check the error log.  I looked for freeware file sorting utilities, but everything was shareware.  I was only planning to do this once, and didn't want to spend $30 for the privilege.  I did download and try one shareware program called Sort Text Lists Alphabetically Software (price $29.99), but it hung, probably because my text file had too many lines.  After 45 minutes or so, I killed it.

Eventually, I found I was able to do the sort very quickly using the SORT command in Ubuntu.  (I was running WinXP inside a VMware virtual machine on Ubuntu 9.04, so switching back and forth between the operating systems was just a matter of a click.)  The sort command I used was like this:
sort -b -d -f -i -o SORTEDFILE.TXT INPUTFILE.TXT
That worked.  I edited SORTEDFILE.TXT using Ubuntu's GEDIT program (like WinXP's Notepad).  For some reason, PrintFolders (or something) had inserted a lot of lines that did not match the expected pattern of D:\FOLDER\SUBFOLDER\FILENAME.EXT.  These may have been shortcuts or something.  Anyway, I removed them, so everything in SORTEDFILE.TXT matched the pattern.

Now I wanted to parse the lines.  My purpose in doing the file list and analysis was to see if I had any files that had the same names but different extensions.  I suspected, in particular, that I had converted some .doc and .jpg files to .pdf and had forgotten to zip or delete the original .doc and .jpg files.  So I wanted to get just the file names, without extensions, and line them up.  But how?  Access and Excel still couldn't handle the list.

This time around, I took a look at the Access error log mentioned in its error message (above).  The error, in every case, was "Field Truncation."  According to a Microsoft troubleshooting page, truncation was occurring because some of the lines in my text file contained more than 255 characters, which was the maximum Access could handle.  I tried importing into Access again, but this time I chose the Fixed Width option rather than Delimited.  It only went as far as 111 characters, so I just removed all delimiting lines in the Import Text Wizard and clicked Finish.  That didn't give me any errors, but it still truncated the lines.  Instead of File > Get External Data > Import, I tried Access's File > Open command.  Same result.

I probably could have worked through that problem in Access, but I had not planned to invest so much time in this project, and anyway I still wasn't sure how I was going to use Access to remove file extensions and folder paths so that I would just have filenames to compare.  I generally used Excel rather than Access for that kind of manipulation.  So I considered dividing up my text list into several smaller text files, each of which would be small enough for Excel to handle.  I'd probably have done that manually, by cutting and pasting, since I assumed that a file splitter program would give me files that Excel wouldn't recognize.  Also, to compare the file names in one subfile against the file names in another subfile would probably require some kind of lookup function.

That sounded like a mess, so instead I tried going at the problem from the other end.  I did another directory listing, this time looking only for PDFs.  I set the file filter to *.pdf in PrintFolders.  I still couldn't fit the result into Excel, so I did the Ubuntu SORT again, this time using a slightly more economical format:
sort -bdfio OUTPUTFILE.TXT INPUTFILE.TXT
This time, I belatedly noticed that PrintFolders and/or I had somehow introduced lots of duplicate lines, which would do much to explain why I had so many more files than I would have expected.  As advised, I used another Ubuntu command:
sort OUTPUTFILE.TXT | uniq -u
to remove duplicate lines.  But this did not seem to make any difference.  Regardless, after I had cleaned out the junk lines from OUTPUTFILE.TXT, it did all fit into Excel, with room to spare.  My import was giving me lots of #NAME? errors, because Excel was splitting rows in such a way that characters like "-" (which is supposed to be a mathematical operator) were the first characters in some rows, but were followed by letters rather than numbers, which did not compute.  (This would happen if e.g., the split came at the wrong place in a file named "TUESDAY--10AM.PDF."  So when running the Text Import Wizard, I had to designate each column as a Text column, not General.

I then used Excel text functions (e.g., MID and FIND) on each line, to isolate the filenames without pathnames or extensions.  I used Excel's text concatenations functions to work up a separate DIR command for each file I wanted to find.  In other words, I began with something like this:
D:\FOLDER\SUBFOLDER\FILENAME.EXT

and I ended with something like this:
DIR "FILE NAME."* /b/s/w >> OUTPUT.TXT

The quotes were necessary because some file names have spaces in them, which confuses the DIR command.  I forget what the /b and other options were about, but basically they made the output look the way I wanted.  The >> told the command to put the results in a file called OUTPUT.TXT.  If I had used just one > sign then that would have meant I wanted OUTPUT.TXT to be recreated every time a match was found.  Using two >> signs was an indication that OUTPUT.TXT should be created if it does not yet exist, but otherwise the results of the command should just be appended to whatever is already in OUTPUT.TXT.

In cooking up the final batch commands, I would have been helped by the MCONCAT function in the Morefunc add-in, but I didn't know about it yet.  I did use Morefunc's TEXTREVERSE function in this process, but I found that it would crash Excel when the string it was reversing was longer than 128 characters.  Following other advice, I used Excel's SUBSTITUTE command instead.

I took the thousands of resulting commands (such as the DIR FILENAME.* >> OUTPUT.TXT shown above), one for each file type (e.g., FILE NAME.*) that I was looking for, into a DOS batch file (i.e., a text file created in Notepad, with a .bat extension, saved in ANSI format) and ran it.  It began finding files (e.g., FILENAME.DOC, FILENAME.JPG) and listing them in OUTPUT.TXT.  Unfortunately, this thing was running very slowly.  Part of the slowness, I thought, was due to the generally slower performance of programs running inside a virtual machine.  So I thought I'd try my hand at creating an equivalent shell script in Ubuntu.  After several false starts, I settled on the FIND command.  I got some help from the Find page in O'Reilly's Linux Command Directory, but also found some useful tips in Pollock's Find tutorial.  It looked like I could recreate the DOS batch commands, like the example shown above, in this format:

find -name "FILE NAME.*" 2>/dev/null | tee -a found.txt

The "-name" part instructed FIND to find the name of the file.  There were three options for the > command, called a redirect:  1> would have sent the desired output to the null device (i.e., to nowhere, so that it would not be visible or saved anywhere), which was not what I wanted; 2> sent error messages (which I would get because the lost+found folder was producing them every time the FIND command tried to search that folder) to the null device instead; and &> would have sent both the standard output and the error messages to the same place, whatever I designated.  Then the pipe ("|") said to send everything else (i.e., the standard output) to TEE.  TEE would T the standard output; that is, it would send it to two places, namely, to the screen (so that I could see what was happening) and also to a file called found.txt.  The -a option served the same function as the DOS >> redirection, which is also available in Ubuntu's BASH script language, which is what I was using here:  that is, -a appended the desired output to the already existing found.txt, or created it if it was not yet existing.  I generated all of these commands in Excel - one for each FILE NAME.* - and saved them to a Notepad file, as before.  Then, in Ubuntu, I made the script executable by typing "chmod +x " at the BASH prompt and then ran it by typing "./" and it ran.  And the trouble proved to be worthwhile:  instead of needing a month to complete the job (which was what I had calculated for the snail's-pace search underway in the WinXP virtual machine), it looked like it could be done in a few hours.

And so it was.  I actually ran it on two different partitions, to be sure I had caught all duplicates.  Being cautious, I had the two partitions' results output to two separate .txt files, and then I merged them with the concatenation command:  "cat *.txt > full.lst."  (I used a different extension because I wasn't sure whether cat would try to combine the output file back into itself.  I think I've had problems with that in DOS.)  Then I renamed full.lst to be Found.txt, and made a backup copy of it.

I wanted to save the commands and text files I had accumulated so far, until I knew I wouldn't need them anymore, so I zipped them using the right-click context menu in Nautilus.  It didn't give me an option to simultaneously combine and delete the originals.


Next, I needed to remove duplicate lines from Found.txt.  I now understood that the command I had used earlier (above) had failed to specify where the output should go.  So I tried again:

sort Found.txt | uniq -u >> Sorted.txt

This produced a dramatically shorter file - 1/6 the size of Found.txt.  Had there really been that many duplicates?  I wanted to try sorting again, this time by filename.  But, of course, the entries in Sorted.txt included both folder and file names, like this:

./FOLDER1/File1.pdf
./SomeotherFolder/AAAA.doc
Sorting normally would put them in the order shown, but sorting by their ending letters would put the .doc files before the .pdfs, and would also alphabetize the .doc files by filename before foldername.  Sorting them in this way would show me how many copies of a given file there had been, so that I could eyeball the possibility that the ultimate list of unique files would really be so much shorter than reported in Found.txt.  I didn't know how to do that in bash, so I posted a question on it.


Meanwhile, I found that the output of the whole Found.txt file would fit into Excel.  When I sorted it, I found that each line was duplicated - but only once.  So plainly I had done something wrong in arriving at Sorted.txt.  From this point, I basically did the rest of the project in Excel, though it belatedly appeared that there were some workable answers in response to my post.