Search code examples
macostextapplescript

How to re-format a .txt list in Applescript


I have a file (list.txt) with a list that contains thousands of lines that look like this:

carpet-redandblue
shelf-brown
metaldesk-none

Is there a script I can use to remove everything after the "-", including the "-" as well?

This is what I have so far:

set theFile to "/Users/home/Desktop/list.txt"
if theFile contains "-" then
    set eol to "-"
else
    set eol to "-"
end if

But doesn't seem to be working. Do I have to define an output file with a filename and path?


Solution

  • This should do what you need, at least as I understand it. The script reads the text file into a variable. It then breaks the text into paragraphs (or lines) and splits each line at the first dash. It then converts each line back into paragraphs of a text. Finally, it writes the resulting text to a text file. If you prefer to use the resulting text in some other way, it is stored in the prunedText variable.

    use scripting additions
    
    (*
    set rawText to "carpet-redandblue
    shelf-brown
    metaldesk-none"
    *)
    set rawText to read file ((path to desktop as text) & "list.txt")
    
    set AppleScript's text item delimiters to "-"
    set paraText to paragraphs of rawText
    --> {"carpet-redandblue", "shelf-brown", "metaldesk-none"}
    
    set wordPara to {}
    repeat with eachLine in paraText
        set end of wordPara to first text item of eachLine
    end repeat
    --> {"carpet", "shelf", "metaldesk"}
    
    set AppleScript's text item delimiters to linefeed
    set prunedText to wordPara as text
    (*
     "carpet
    shelf
    metaldesk"
    *)
    
    -- optionally
    tell application "Finder"
        set nl to ((path to desktop as text) & "newList.txt") as «class furl»
    end tell
    
    close access (open for access nl)
    write prunedText to nl as text