How to re-format a .txt list in Applescript - macos

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?

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

This in my opinion is the easiest solution.
Open Terminal.app
Go to Finder and while holding the ⌘ key, drag and drop the folder containing your "list.txt" file directly into a Terminal window. This will change your current working directory in Terminal to the folder containing your "list.txt" file.
Then paste this following code into that Terminal window and press the Return key...
grep -E -o "^\w*" list.txt > new_list.txt
This will create a new file called "new_list.txt" with the hyphens and everything after them removed from each line of your original list.txt

Related

Exchange filename position

I want to exchange hundreds of filename positions of a file in FolderX.
The file names are all created on this way: pos1.pos2.pos3.pos4.pos5.pos6.pdf
example: (GK.19.kkla.0715.nr.36053342.zg.119.pdf)
I would like to exchange some positions so that it changes to: pos4.pos2.pos5.pos6.pos3.pos1.pdf
As an example, a command such as; exchange pos3->pos6 or pos1->pos4
I looked in the Automator, but it can only add before or after file names, but no positions exchange.
maybe AppleScript? Thanks for inputs.
The following solution uses AppleScript's text item delimiters and System Events. It is quite fast, and has the advantage of avoiding throwing an error when the filename of some file in a folder does not match the desired pattern. Also, it works with pdfs of the folder.
set folderHFS to (choose folder) as text
set {ATID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "."}
tell application "System Events"
repeat with aFile in (get files of folder folderHFS whose name extension is "pdf")
try
set {pos1, pos2, pos3, pos4, pos5, pos6, ext} to text items of (get name of aFile)
set name of aFile to {pos4, pos2, pos5, pos6, pos3, pos1, ext} as text
end try
end repeat
end tell
set AppleScript's text item delimiters to ATID
You could use AppleScript (scripting Finder/System Events to traverse the files and text item delimiters to split up each file name), or you could do it with a shell script, which has the advantage of being much quicker:
#!/bin/sh
for f in /path/to/input/folder/*; do
n=`basename "$f" | awk -F '.' '{ print $4"."$2"."$5"."$6"."$3"."$1".pdf" }'`
mv "$f" "/path/to/output/folder/$n"
done

How to edit multiple files at once using applescript

I have an applescript I am able to use to edit the text in any file by replacing an instance of the text with different text.
Essential, this script should do these things in this order.
Pick a folder.
Pick out all the files with the .txt extension
Reach each file individually and find specific text.
Replace the text with new text.
Close the file and move on to the next file.
The code is below
set aFolder to choose folder "Select folder to be processed"
tell application "Finder" to set allFIles to every file of aFolder whose name extension is in {"txt"}
repeat with someFile in allFIles
set SomeText to (read SomeFile)
set {SearchText, ReplaceText} to {"Searches of this", "Replaces with this"}
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, SearchText}
set {TextItems, AppleScript's text item delimiters} to {text items of SomeText, ReplaceText}
set {SomeText, AppleScript's text item delimiters} to {TextItems as text, TempTID}
set OpenFile to open for access SomeFile with write permission
try
set eof of OpenFile to 0
write (text 1 thru -2 of SomeText) to OpenFile as text
close access OpenFile
on error errmess
log errmess
try
close access OpenFile
end try
end try
end repeat
I want to be able to either select multiple files at once or select a folder and use the script to edit all files within the folder that contain the searched text. Any help is appreciated.
EDIT: I know I can get the script to separate out the .txt files from the rest of the folder contents, and I know I can "see" these files (If I do a display dialog, for example, I can add a variable calling the name of SomeFile and see it in a dialog box) I just cannot read the file so I can edit it. What I need is to be able to open a folder, find all .txt files, open them, edit the text by replacing one instance of a specific word/phrase with another, and close the file before moving on to the next one.
You can select folder and process all files in it with this script:
set aFolder to choose folder "Select folder to be processed"
tell application "Finder" to set allFIles to every file of aFolder whose name extension is in {"txt"}
repeat with someFile in allFIles
-- do here what you need for someFile (alias) !!
-- you can cut/paste your current script here
end repeat

Merging files in Applescript

I am trying to do below in AppleScript.
Concatenate/Merge all *.xxx files found in a particular folder into one new file
Each file contains a header. Strip header from all but 1st file before merging.
Add a footer text to the merged file.
This sounds relatively simple in other languages but I am a beginner to applescript. Any help to find a direction would be appreciated.
TIA
AnuRV
Try this, you are prompted to choose a base folder and a destination file name.
Important: Use a destination location outside the base folder to avoid the file to be included in the merging process.
I assume that your tsv file type is a typo and you mean csv.
If not, change all occurrences of csv in the script.
The text delimiter is linefeed (0A), if you need return (0D) change the occurrence of linefeed to return.
set baseFolder to choose folder
set destinationFile to choose file name with prompt "Choose destination file name" default name "merged.csv"
tell application "Finder" to set tsvFiles to (files of baseFolder whose name extension is "csv") as alias list
set text item delimiters to linefeed
try
set fileDescriptor to open for access destinationFile with write permission
repeat with i from 1 to (count tsvFiles)
set theFile to item i of tsvFiles
set theText to paragraphs of (read theFile as «class utf8»)
if i = 1 then
write (theText as text) to fileDescriptor as «class utf8»
else
write ((items 2 thru -1 of theText) as text) to fileDescriptor as «class utf8»
end if
end repeat
close access fileDescriptor
on error
try
close destinationFile
end try
end try
set text item delimiters to {""}

"Can't get last text item of alias" Error When Running AppleScript

I have an AppleScript that runs as part of a Hazel routine monitoring a folder. When the script runs, it picks apart the file targeted by the Hazel routine and then attaches the file to an email and addresses the email with information from the name of the file. Unfortunately, it seems there is an error somewhere in the script, but I cannot seem to locate it.
The only semi-useful information from Console is in the title (i.e., "Can't get last text item of alias"). Here is the script:
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
set FileName to theFile
--remove trailing slash
set SansSlash to quoted form of text 1 through -2 of FileName
set FileName to SansSlash as text
-- remove path from FileName
set AppleScript's text item delimiters to ":"
set SansPath to last text item of FileName
set FileName to SansPath as text
-- remove extension
set AppleScript's text item delimiters to "."
set SansExtension to every text item of FileName
set last text item of SansExtension to ""
set FileName to SansExtension as text
-- parse using —
set AppleScript's text item delimiters to "—"
set clientName to first text item of FileName
set clientEmail to last text item of FileName
tell application "Airmail 2"
activate
set theMessage to make new outgoing message with properties {subject:"New Invoice from ", content:"Please find attached, infra, the current month's invoice. If you have any questions, please feel free to respond to this email. One-time payments may be made using the following secure form on our website: https://. Thank you for your continued business."}
tell theMessage
set sender to "billing#example.com"
make new to recipient at end of to recipients with properties {name:clientName, address:clientEmail}
make new mail attachment with properties {filename:theAttachment1}
compose
end tell
end tell
end hazelProcessFile
The code is commented, so it should be obvious what each section is supposed to do. I would imagine the issue is in the "remove path from FileName" section, as that is the section that has been giving me the most trouble.
theFile is obviously an alias specifier.
text item and text thru – as the name implies – expects plain text
You have to coerce the alias first to text before dealing with text and remove quoted form of, that's only needed in conjunction with do shell script.
--remove trailing slash
set FileName to theFile as text
set SansSlash to text 1 through -2 of FileName
set FileName to SansSlash
but there is no trailing slash in a HFS path
To strip the file name without extension from an alias this is much easier
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set baseName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
Edit:
Try this optimized code, the Airmail 2 part is skipped and I don't know if the EM Dash character is treated correctly in case you'll copy and paste the code.
on hazelProcessFile(theFile)
set theAttachment1 to (POSIX path of theFile)
tell application "System Events" to set {name:Nm, name extension:Ex} to theFile
set FileName to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
-- parse using —
set {TID, text item delimiters} to {text item delimiters, "—"}
set clientName to text item -2 of FileName
set clientEmail to text item -1 of FileName
set text item delimiters to TID
-- tell application "Airmail 2"
-- ...
end hazelProcessFile

applescript get rid of full path

I've got a choose file in my AppleScript. When I run the script and choose a file, the output is always the full file path with the file extension on the end. For example:
Macintosh HD:Developer:About Xcode.pdf
is what I don't want. I only want:
About Xcode
The below answer by Kassym Dorsel doesn't work when there is more than one . in it.
The below answer by Lri doesn't work with set x to choose file:
error "Can’t make quoted form of alias \"Macintosh HD:Applications:Firefox.app:\" into type Unicode text." number -1700 from quoted form of alias "Macintosh HD:Applications:Firefox.app:" to Unicode text
You can use the Finder to manipulate the names of Finder items:
choose file with prompt "Pick one"
set filepath to result
tell application "Finder" to set {dispName, nameExt, isHidden} to ¬
the {displayed name, name extension, extension hidden} of the filepath
if isHidden or nameExt is equal to "" then
dispName
else
(characters 1 through (-2 - (count of nameExt)) of dispName) as text
end if
set baseName to result
This will work :
set a to "Macintosh HD:Developer:About.Xcode.pdf"
set text item delimiters to ":"
set temp to last text item of a
set text item delimiters to "."
set temp to text items 1 thru -2 of temp as text
Gives => About.Xcode

Resources