Search code examples
shellapplescriptautomator

Read a text file with Automator.app line by line


I'm a novice at coding so please be patient with me.

I've created a Workflow with Automator (OSX) which works fine. The only issue I have is that I want it to run on a number of inputs (that is as a batch). I've inserted the Loop action but the problem I'm having is about changing the initial input each time.

I would like to use an applescript to automate the insertion of the initial input each time.

I have a TXT file with URLs. With an apple script, I'd like to copy a URL (or a line of text) to clipboard. In the next iteration I'd like to copy the next URL (or line of text).

Can anyone help?

Thank you!!


Solution

  • You can create one looping workflow (called as LinesToClipboard.workflow) what will

    • get a line from an text file (not rtf, or doc)
    • copy the line to clipboard
    • run your current workflow
    • loop again for the next line

    The workflow:

    • Create new automator workflow
    • create a variable
      • at the bottom find the icon "Show or hide the workflow variables list" and show the workflow wariables (empty)
      • right click and "New variable..."
      • name the variable as "LineNumber"
    • add actions:
      • Get Value of Variable (LineNumber)
      • Run Shell Script
      • shell: /bin/bash
      • important: change the Pass input to as arguments
      • add the following content (copy exactly, with all quotes and such):
      • in the content of script, change the /etc/passwd to the full path of your filename, like /Users/myname/Documents/myfile.txt
      • at the end of this action the clipboard will contain one line from the file
    linenum=${1:-0}
    filename="/etc/passwd" # full path of your text-filename
    let linenum++
    sed -n "${linenum}p" < "$filename" | pbcopy
    echo $linenum
    
    • Set Value of Variable (LineNumber)
    • Run Workflow - add your current workflow (or the "ShowClipboard.workflow" - see bellow)
      • the Wait for workflow to finish should be checked
      • important The Output menu should be: "Return action input"
    • Loop
      • add your count...
    • Run Shell Script (Ignore this action's input), content one line: echo 0 (This will reset the variable LineNumber to zero, when the loop ends)
    • Set Value of Variable (LineNumber)

    For testing, you can create another workflow, called ShowClipboard.workflow, with an content:

    • Get Contents of Cliboard
    • Set Value of Variable (clipval)
    • Ask for confirmation (and drag the (clipval) to the Message field)

    Run the first workflow.

    Screenshots (for sure) :)

    enter image description here

    The second workflow (for testing)

    enter image description here