Append text to file from command line without using io redirection

LinuxCommand LineFile Io

Linux Problem Overview


How can we append text in a file via a one-line command without using io redirection?

Linux Solutions


Solution 1 - Linux

If you don't mind using sed then,

$ cat test
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test
$ cat test
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

Solution 2 - Linux

If you just want to tack something on by hand, then the sed answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):

Using Perl:

perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt

N.B. while the >> may look like an indication of redirection, it is just the file open mode, in this case "append".

Solution 3 - Linux

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

Solution 4 - Linux

You can use Vim in Ex mode:

ex -sc 'a|BRAVO' -cx file
  1. a append text

  2. x save and close

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionapoorv020View Question on Stackoverflow
Solution 1 - LinuxtaskinoorView Answer on Stackoverflow
Solution 2 - LinuxJoel BergerView Answer on Stackoverflow
Solution 3 - LinuxOndra ŽižkaView Answer on Stackoverflow
Solution 4 - LinuxZomboView Answer on Stackoverflow