How to remove end-of-line character from unix text file?

I know that this kind of question has been covered in other posts, but after much study, I still can’t figure out exactly the technique I need.

I am working on a script that creates a one-line text file, like this.

do shell script "echo myVariable > somefile"

The next time the script is run, it reads the content of myVariable from the file like this:

set openMyFile to (open for access (POSIX file myFile))
	set myString to (read openMyFile for (get eof myFile)) as string
	close access openMyFile

I then want to append a string to the text that I have read from the file, but the text that I have read from the file ends in a carriage return.

My question is: how can I remove the carriage return from the string? I can see that I need set AppleScripts’ text item delimiters to ASCII character 13, but that is as far as I can get. I can’t remove the carriage return from the text.

I will be grateful for any help with this simple problem.



read file myFile using delimiter return

or (more flexible, because it considers all new line characters)

paragraphs of (read file myFile)

myFile is assumed to be a HFS path.
open for access is not needed

I think your problem is also that normally every command in the shell ends with a newline including echo command. Quite useful when you want a log

do shell script "echo myvariable >> somefile"

Now we append myvariable to the end of the file. Because echo prints out a newline every line added to the file starts on a newline. So it’s quite useful this behavior.

If you don’t want this you need the echo command in /bin folder and not the built in echo command. Then you need to tell echo you don’t want a trailing newline with option -n

do shell script "/bin/echo -n myvariable >> somefile"

Now myvariable will be written to the end of the file without a trailing newline and therefore when you run the script a second time the content of placed without newlines in between.

Many thanks for both of these extremely useful replies. I am now going to simplify some of my older scripts - I wish I had known these things before.

Thank you again!

Just a footnote. The solution that I found most useful for this purpose (reading a one-line text file) was this:

set myString to paragraph 1 of (read file myFile)

This solved it perfectly. Thank you again.