Home > other >  How to re-format a .txt list in Applescript
How to re-format a .txt list in Applescript

Time:10-17

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?

CodePudding user response:

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

CodePudding user response:

This in my opinion is the easiest solution.

  1. Open Terminal.app
  2. 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.
  3. Then paste this following code into that Terminal window and press the Return key...

while read line ;do echo "$line" |cut -d "-" -f 1 ;done < 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