goombado

Q: Test for specific character in Applescript

Hi Applescript Community!

 

I am attempting to write a code in which a different action will occur depending on the 1st character of a .txt file. This is my code so far (I'm fairly new to Applescript so I'm sorry if this is a basic question)

tell application "TextEdit"

  if first character of "/Users/Goombado/Documents/applescript_test.txt" is 1 then

  display dialog "Hi"

  else

  display dialog "Hello"

  end tell

  end if


Is it possible to do this in Applescript?

Thanks in advance,

 

Andrei

MacBook Air, OS X Mavericks (10.9.1)

Posted on Sep 25, 2016 4:02 AM

Close

Q: Test for specific character in Applescript

  • All replies
  • Helpful answers

  • by VikingOSX,Helpful

    VikingOSX VikingOSX Sep 26, 2016 3:33 AM in response to goombado
    Level 7 (21,056 points)
    Mac OS X
    Sep 26, 2016 3:33 AM in response to goombado

    set this to read "/Users/Goombado/Documents/applescript_test.txt"

    if this begins with "1" then

         display dialog "Hi"

    else

         display dialog "Hello"

    end if

  • by Hiroto,Solvedanswer

    Hiroto Hiroto Sep 26, 2016 3:33 AM in response to goombado
    Level 5 (7,306 points)
    Sep 26, 2016 3:33 AM in response to goombado

    Hello

     

    It will depend upon the text encoding of the file. If it is in UTF-16, it may contain BOM. Even if it is in UTF-8, it may contain quasi BOM.

     

    The following code assumes the file contains text encoded in UTF-8 without quasi BOM.

     

    set f to "/path/to/file.txt"
    set t to read POSIX file f as «class utf8»
    if t starts with "1" then
        display dialog "Hi"
    else
        display dialog "Hello"
    end if
    

     

     

    Regards,

    H

     

     

    PS. Alternatively,

     

    set f to "/path/to/file.txt"
    set t to read (f as POSIX file) as «class utf8»
    if t's character 1 = "1" then
        display dialog "Hi"
    else
        display dialog "Hello"
    end if
    

     

    EDIT: added PS.