Home > Enterprise >  How to get name of folder for Shell Script in Automator?
How to get name of folder for Shell Script in Automator?

Time:08-04

I'm using the newest version of macOS Monterey.

Sometimes I have to merge/combine all files that are in a specific folder into one txt file.

I currently do that by typing this in Terminal:

cd /Users/my_name/Desktop/test_folder ; cat * >merged.txt

This will merge/combine all files in folder test_folder into one file called merged.txt. The file merged.txt will get saved into the folder test_folder.

Every time I need this I have to open Terminal copy/paste the command and replace test_folder with the right folder name, since it's not always the same.

I want to make this easier by just make a right click on a folder, go to Quick Actions and select e.g. Merge all files to merge/combine all files inside the folder I just clicked on.

But I stuck at getting the folder name. How can I dynamically get the folder name and path I clicked on to start this Quick Action instead of the hard coded /Users/my_name/Desktop/test_folder?

Or, is there another and easier solution?

This is what I have so far:

Automator

CodePudding user response:

I wouldn’t do this with AppleScript, especially if all it’s ultimately doing is calling out to a shell script.

Stick with the Run Shell Script action except change the option for passing the input as arguments rather than to stdin.

The folders selected in Finder will then be available to your script via $@, so you can do something like:

for d in "$@"; do
    cat "$d"/* > "$d/merged.txt"
    open -R "$d/merged.txt"
done 2>/dev/null

This loops through the selected directories and concatenates the files to merged.txt in the respective directory. The open -R line reveals the merged.txt file in Finder.

Errors are written to /dev/null, i.e. discarded, as cat will throw an error if any of the directories, themselves, contain directories.

CodePudding user response:

Instead of adding a Run Shell Script to your workflow, try adding a Run AppleScript command instead. Copy this following AppleScript code to the Run AppleScript command.

on run {input, parameters}
    try
        do shell script "cd " & quoted form of POSIX path of input & " && cat *.txt > merged.txt"
    on error
        try
            do shell script "cd " & quoted form of POSIX path of input & " && rm merged.txt"
        end try
    end try
end run

enter image description here

  • Related