Your original question was how to
avoid appending to a new line, you know, which is why we gave you lines that don't.
Code:
f="$(<$fileName)" ; echo "${f%$'\n'} $appendThis" >$fileName
^ ^ ^
#1 #2 #3
#1) This parameter substitution pattern
removes a single newline from the end of the variable text
if it exists. Remember that newline is just an ascii character (0x0A--LineFeed) like any other, just a non-printing one, so text manipulations can affect it as well.
But, mea culpa, I've discovered the parameter substitution isn't actually necessary, because it turns out that the
$(..) process substitution used to set
f automatically removes any trailing newlines anyway. So
echo "$f $appendThis" works just the same.
If you want to be able to have it remove newlines by default, but also be able to voluntarily append one if you want, insert a newline at the beginning of the replacement variable instead.
Code:
appendThis=$'\nBob'
#2) The echo command prints the contents of
$f, then a
space, then the contents of
$appendThis. Simply remove the space to have them concatenated directly together; "
$f$appendThis".
The sed command used a similar technique; the replacement string was pre-appended by a space so that it
wouldn't concatenate directly with the original text. I pointed that out in my first post.
Note that you can also add spaces to the beginning of the replacement variable instead if you want them to appear only on demand.
#3)
> redirects the output to the specified file,
overwriting anything that existed previously. Compare to
>> which
appends text to the current file instead.
Pretty much every shell tool you use will print to stdout and not modify the original by default. You need to use a redirect, or a tool's built-in ability to output to file or edit the original if it exists, like sed's
-i, to print back to a file. Sometimes you need to print the output to a temporary file first, then replace the original with it afterwards (this is actually what sed is doing when you use -i).
Finally, as for the size of the file, it's mostly limited by the amount of RAM you have. I don't think bash has any hard limit for string variables, so you should be good up to several megabytes at least. It's really only a concern with super-large (gigabyte-sized) files that can overwhelm the system's memory capacity.