Search code examples
macosapplescriptautomator

Extract specific row from clipboard with AppleScript


I'm using the following code to get the content of my clipboard into my Automator code:

set theString to get the clipboard
set {TID, text item delimiters} to {text item delimiters, ";"}
set theList to text items of theString
set text item delimiters to TID

However, if the user has copied the following lines:

word1;word2;word3
word4;word5;word6

How do I extract the second row only? I'm not interested in the first row, and the number of columns can change.


Solution

  • The following example AppleScript code works for me:

    set myTextItemDelimiter to ";"
    
    if (clipboard info for string) is {} then
        display dialog ¬
            "The clipboard does not contain text." buttons {"OK"} ¬
            default button 1 giving up after 5
        return
    end if
    
    set theString to (the clipboard) as string
    
    if theString does not contain myTextItemDelimiter then
        display dialog ¬
            "The clipboard does not contain the \"" & ¬
            myTextItemDelimiter & "\" delimiter." buttons {"OK"} ¬
            default button 1 giving up after 5
        return
    end if
    
    if (count paragraphs of theString) is greater than 1 then
        set theString to paragraph 2 of theString
    else
        display dialog ¬
            "The clipboard only contains one line of text." buttons {"OK"} ¬
            default button 1 giving up after 5
        return
    end if
    
    set {TID, text item delimiters} to {text item delimiters, myTextItemDelimiter}
    set theList to text items of theString
    set text item delimiters to TID
    
    return theList
    

    Notes:

    I added some error handling to the code.