2

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • echo -n "line" >> file will avoid placing an additional newline at the end. – ctrl-alt-delor Jul 22 '16 at 23:49
  • @don_crissti The title says after last character, the body suggests otherwise. So let us ask the questioner. user3669481 can you clarify for us? – ctrl-alt-delor Jul 23 '16 at 00:02
  • OP pretty clearly meant "last character" to mean the last visible character, not considering that most people would consider the newline to be the last character – Michael Mrozek Jul 23 '16 at 06:37

2 Answers2

5

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.

John1024
  • 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
1

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 "$!";
Zan Lynx
  • 597
  • 1
  • 6
  • 14