Create text file using variables

Hello,


I need to create a new file with a paragraph that uses variables. I've tried this:


do shell script "echo Text for the file > ~/desktop/file.txt"


but I don't know how to use the variables and add more than one text lines.


Thanks in advance.

Posted on Nov 3, 2015 4:08 AM

Reply
7 replies

Nov 6, 2015 9:39 AM in response to Jose Corbalán

This is a side effect of how echo (or, more precisely, the shell) parses the data - quotes are used to separate text strings and it would not normally expect to pass them through. You get the same result if you typed a quoted string on the command line.


The standard solution for this is to escape the quotes so that they're passed through the shell, through echo, and out to your file. Since you're escaping characters in AppleScript that are passed to the shell, which also needs to escape them, you need to double-escape, like:


set myQuotedString to "A string with \"quotes\""

do shell script "echo " & myQuotedString & " > ~/Desktop/some.txt" --> fails to include quotes


set myQuotedString to "A string with double-escaped \\\"quotes\\\"" --> note the extra backslashes

do shell script "echo " & myQuotedString & " > ~/Desktop/some2.txt" --> bingo!

That's a PITA, though. An easier solution is to just not use the shell and write it directly via AppleScript:

set myQuotedString to "A string with \"quotes\""


set myfile to open for accessfile ((path todesktopastext) & "some3.txt") with write permission

set eofmyfileto 0

writemyQuotedStringtomyfile

close accessmyfile

Nov 3, 2015 2:14 PM in response to Jose Corbalán

It is simple.


1) You need to escape two characters in AppleScript string literal, i.e., backslash (\ U+005C REVERSE SOLIDUS) and quotation mark (" U+0022 QUOTATION MARK).


2) You may use 'quoted form' property of string class in AppleScript to generate single-quoted string to be used in shell.



E.g.,


--set t to "\"Hello,\\nWorld\"" --set t to quote & "Hello," & linefeed & "World" & quote set t to "\"Hello, World\"" do shell script "echo " & t's quoted form & " >~/Desktop/out.txt"




Regards,

H

Nov 6, 2015 2:28 PM in response to Jose Corbalán

And another variation without a storm of backslashes.


set outfile to POSIX path of ((path to desktop) as text) & "foo.txt"

set textstr to "Reality is merely an illusion, albeit a very persistent one."

do shell script "printf %s " & quote & textstr & return & "Hello World!" & quote & " > " & outfile

Result:

Reality is merely an illusion, albeit a very persistent one.

Hello World!

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Create text file using variables

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.