11

I want to append text to file like echo "abc" >>file.txt.

But this add abc after new line

How can I add abc in the end of file with echo without new line?

  • 2
    The file already has a newline, you are just adding after it. So you will have to replace the newline character from the last line, with “abc”. – ctrl-alt-delor Dec 24 '17 at 19:16
  • Welcome to StackExchange! Your question is good; it would have been better if you specified examples of the content of your file (before addition, what you get after addition, what you wanted instead). I say this because one of the answers is how to add abc without a final newline, which (after reading your question attentively) does not seem to be what you want. – Law29 Dec 25 '17 at 4:06
15

echo "abc" >>file.txt puts a newline after abc, not before. If you end up with abc on its own line, that means that the newline before abc was already present in file.txt.

Note that it is perfectly normal for a text file to end in a newline. On unix, a line consists of a sequence of characters other than null⁰ or newline followed by a newline.1 Therefore any non-empty text file ends with a newline character.

If you want to add text to the last line of a file, then you can't do it with >>, because this always appends to the file, so it always writes after the last newline. Instead you need a tool that is capable of modifying an existing file. For example, you can use sed:

sed '$ s/$/abc/' file.txt >file.txt.new && mv file.txt.new file.txt

In the sed command, the first $ means “do the following command only on the last line”, the command s/REGEX/REPLACEMENT/ replaces REGEX by REPLACEMENT, and the regular expression $ matches at the end of the line.

Linux's sed command has a built-in feature to automate this create-new-file-and-replace sequence, so you can shorten that to

sed -i '$ s/$/abc/' file.txt

That's a null byte, which ASCII calls NUL and Unicode calls U+0000. Text processing programs may or may not cope with this character.
1 See the definitions of Text File, Line, and Newline Character in the "Definitions" section of the Base Definitions chapter of IEEE 1003.1-2008:2016.

  • 1
    Is your second paragraph meant to imply that a file which doesn't end with a newline is not a text file? E.g. if I take an existing ASCII text file which ends with a new line and append a single byte 0x41 (ASCII 'A'), it's technically no longer a text file? If so, I'd suggest emphasizing that point since it's kind of an unintuitive definition; if not, a slight change in wording might help avoid the confusion. – David Z Dec 25 '17 at 11:07
  • 2
    @DavidZ: That is the standard definition of a text file in Unixland. IIRC it's even in POSIX somewhere. – Kevin Dec 25 '17 at 12:56
  • @Kevin Interesting, I'd never heard that before. Well, even if it is standard, I do think it's kind of unintuitive. – David Z Dec 25 '17 at 23:13
11

I don't think it's possible with echo command, use the following sed approach instead:

sed -i '$ s/$/abc/' file.txt
  • -i - modify the file inplace
  • $ - indicate the last record/line
  • s/$/abc/ - substitute the end of the line $ with substring abc (for the last record)
  • 2
    Note that "in place" doesn't really mean in place. It means "write the edited content to a temporary named file alongside the existing file and then replace it". You can prove this by looking at the inodes with date >file; ls -i file; sed -i 's/201/ZZZ/' file; ls -i file – roaima Dec 25 '17 at 0:47
  • @roaima, I'm aware about sed changing inode number. – RomanPerekhrest Dec 25 '17 at 6:38
  • 2
    I thought you would have been, but i was concerned that with your emphasis of inplace the OP night think it could be used to avoid double disk space use, eg with a large file. – roaima Dec 25 '17 at 8:51
  • @roaima, night think -> might think ... – RomanPerekhrest Dec 25 '17 at 8:56
9

If you have the truncate command and your text file has NL as its last character you can remove it and then append your text like this:

truncate --size -1 file.txt
echo "abc" >>file.txt

(Note that truncate cares nothing about file content, and in this example simply reduces the file size by one byte. If your last character is not a single byte, ie it's a multi-byte "wide" character then you will introduce corruption.)

7

Assuming that the file does not already end in a newline and you simply want to append some more text without adding one, you can use the -n argument, e.g.

echo -n "some text here" >> file.txt

However, some UNIX systems do not provide this option; if that is the case you can use printf, e.g.

printf %s "some text here" >> file.txt

(the initial %s argument being to guard against the additional text having % formatting characters in it)

From man echo (on macOS High Sierra):

-n

Do not print the trailing newline character. This may also be achieved by appending '\c' to the end of the string, as is done by iBCS2 compatible systems. Note that this option as well as the effect of '\c' are implementation-defined in IEEE Std 1003.1-2001 ("POSIX.1") as amended by Cor. 1-2002. Applications aiming for maximum portability are strongly encouraged to use printf(1) to suppress the newline character.

  • It quite obviously does end with a newline. echo -n would put no newline at the end of abc, but abc would still be preceded by a newline, which is what the user wants to avoid. – Kusalananda Jul 14 '18 at 8:53
  • @Kusalananda My answer was more using the assumption that the OP would try to change their process such that the spurious \n didn't show up in the first place. More options are better, especially when they don't involve having to rewrite the entire file every time a change happens (which can get rather slow and run in polynomial time if it's done repeatedly). – fluffy Jul 16 '18 at 1:02
5

What you want is to add it at the end of the last line, so just before the delimiter of that last line, so just before the last character of the file.

With ksh93, you can do:

echo abc 1<> file >#((EOF - 1))

Where 1<> is the standard operator to open a file in read+write mode (and more importantly without truncation) on stdout and >#((...)) is a ksh93-specific seeking operator (here to seek to before the last byte). Note that echo writes abc<newline> where the a overwrites the newline that was there and echo adds its own newline.

The zsh equivalent:

zmodload zsh/system
{sysseek -w end -u 1 -1 && echo abc} 1<> file

Though for a more exact equivalent, you'd also need to print an error message upon failure to seek:

zmodload zsh/system
if sysseek -w end -u 1 -1; then
  echo abc
else
  syserror -p "$0: $LINENO: seek: "
fi 1<> file
-1

Probably a UUOC but you could also do:

echo "$(cat file.txt)abc" >file.txt

As Gilles points out this command is limited:

This mostly works, but not if there is sometimes a blank line at the end of the file and a blank line immediately before. E.g. a file with a fixed number of lines, where the last line is initially empty and is extended over time, and the next-to-last-line may sometimes be empty.

Additionally be wary of using cat on files you are not familiar with:

Conclusion:

Use sed

  • 2
    This mostly works, but not if there is sometimes a blank line at the end of the file and a blank line immediately before. E.g. a file with a fixed number of lines, where the last line is initially empty and is extended over time, and the next-to-last-line may sometimes be empty. – Gilles Dec 24 '17 at 17:49
  • Should I delete it? I definitely think Roman/your answer is the proper way to go but I know I personally like seeing alternatives, and OP did ask for echo :p – Jesse_b Dec 24 '17 at 17:51
  • 1
    Also this puts the entire file on the command line – n.caillou Dec 24 '17 at 19:34
  • @n.caillou huh? This will not print anything to STDOUT. – Jesse_b Dec 24 '17 at 20:54
  • 2
    Well, none of those vulnerabilities are really related to cat, but to issues with arbitrary escape sequences being sent to the terminal. – ilkkachu Dec 24 '17 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.