create and format the contents of a text file

OS 10.11.5
Script Editor Version 2.8.1 (183.1)
AppleScript 2.5

Hi All: (This may get lengthy, but I always like to supply as much pertinent info as I can.)
So, here’s the scoop.

I have one folder containing about 61 episodes of a particular “old time” radio (OTR) program. Each program file’s name starts with the date it aired as opposed to episode number, in case I am missing some they still are in order. So, for example, one name is “1942-06-08 Washington Woman Spy”.

In applescript I have written a little script to put all the file names into an array/list.

Here’s the goal: I want to put the names into a plain text file named “Programs”. However, I’ want a blank line each time the year changes. in other words.

Other than creating a CSV(sp?) file to import into a spreadsheet and then do a sorting script to accomplish my goal, I do not know how to check only the first 4 characters of the items using only Applescript. I tried a lot of the parsing advise in the forums, Applescript sites, and other methods but to no avail.

Would anybody care to start me on the right track please?

BG

Hi,

assuming var_Episodes contains a list of file names like

property var_Episodes : {"1942-09-14 Spy Submarine Logansport", "1942-12-14 German Spies", "1945-02-14 The Nazi Radio Station"}

try this, I used descriptive variable names so the script is supposed to be self-explanatory


set programsFile to (path to desktop as text) & "Programs.txt"
-- set latest year to the year of the first item
set latestYear to text 1 thru 4 of item 1 of var_Episodes
try
	set fileDescriptor to open for access file programsFile with write permission
	repeat with anEpisode in var_Episodes
		set currentEpisode to contents of anEpisode
		set currentYear to text 1 thru 4 of currentEpisode
		if currentYear is not latestYear then
			-- if there is a new year insert a new line
			set currentEpisode to return & currentEpisode
			set lastestYear to currentYear
		end if
		write currentEpisode & return to fileDescriptor
	end repeat
	close access fileDescriptor
on error
	try
		close access file programsFile
	end try
end try

Thank you StefanK, i’ll give it a shot. If any problems I cannot handle I’ll post into this thread.

My process in creating variables and such come from my programming mainframe 'puters from about 1975 to 2001. For instance I am placing 'var_" in front of a variable name, ‘path_’ for path variables, etc. for simplicity (in my eyes.)

Anyway, your answer will help with another script I started working on.in iTunes I would assign track numbers to the tracks in playlist or album ‘Counterspy’ and then move that date at the beginning of each track name to the comment field as “Aired: 1942-09-14” or whatever the date is, and of course, remove the initial first space in the track name.

Thanks again.

BG