Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append text to file from command line without using io redirection

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

like image 305
apoorv020 Avatar asked Jan 09 '11 15:01

apoorv020


People also ask

How do I append a text file in Linux?

The easiest way to append text is to use the operator ‘ >> ‘ from the Linux command line. There are two different operators that redirects output to files: ‘ > ‘ and ‘ >> ‘, that you need to be aware of.

How do I redirect command line output to a text file?

Redirect Output from the Windows Command Line to a Text File. When you type a command on the Windows command line, the output from the command is displayed in the command prompt window. For some commands, the output can be several rows long and sometimes longer than the height of the command window, causing you to scroll to view all of the output.

How to append a line to a file without overwriting its contents?

In order to append a line to our file.txt and not overwrite its contents, we need to use another redirection operator (>>): Note that the ‘>’ and ‘>>’ operators are not dependent on the echo command and they can redirect the output of any command: Moreover, we can enable the interpretation of backslash escapes using the -e option.

How to append text to a file in DOS?

DOS Command to Append Text to a File 1 cd – change directory 2 echo – send out the following 3 >> – append 4 type – send the contents of the specified file to the console


2 Answers

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
like image 117
taskinoor Avatar answered Oct 21 '22 12:10

taskinoor


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".

like image 26
Joel Berger Avatar answered Oct 21 '22 14:10

Joel Berger