Appending an extra line is simple as I can use echo "line" >> file
but what if I want to add a string right after the last char in the file without starting a new line? What are some good ways to do this?

- 67,283
- 35
- 116
- 255

- 87
- 5
2 Answers
A well-formed unix text file must have a trailing newline at the end of the file. To achieve what you want, the string must be placed before that existing trailing newline.
Consider this test file:
$ cat File
1
2
3
Now, let's add words to the last line before the last newline character:
$ sed '$s/$/new words/' File
1
2
3new words
Or, if you want to edit the file in place, use the -i
option:
sed -i.bak '$s/$/new words/' File
How it works:
$
The first
$
tells sed to only perform the command which follows on the last line of the file.s/$/new words/
For that last line in the file, this places
new words
at the end of the line but before the final newline character.In a substitute command,
$
means end of the line.

- 74,655
-
Excellent answer! I am faux-XML tagging some plain text (processed emails) so that I can import it more easily into PostgreSQL -- somewhat analogously to my SO answer at https://stackoverflow.com/questions/19007884/import-xml-files-to-postgresql/49950384#49950384. My input file (e.g.) is: "Unclogging the body's protein disposal system ... in patients with AD." I can tag that text with
sed -i '1s/^/<BODY>/ ; $s/$/<\/BODY>/' input_file
, giving "Unclogging the body's protein disposal system ... in patients with AD.". – Victoria Stuart Apr 12 '19 at 23:43
To avoid rewriting the entire file you would seek to the end of the file, back up one character and write.
Doing this with regular Unix shell tools is a bit iffy.
However, there's Perl, which does everything. You could also use Ruby or Python or any other full featured script language.
Perl example:
#!/usr/bin/env perl
use strict;
use Fcntl qw(:seek);
open(F, '+<', 'testfile') or die "$!";
seek(F, -1, SEEK_END) or die "$!";
print F "new data\n";
close(F) or die "$!";

- 597
- 1
- 6
- 14
echo -n "line" >> file
will avoid placing an additional newline at the end. – ctrl-alt-delor Jul 22 '16 at 23:49