2011年3月24日 星期四

Append text to file from command line

http://stackoverflow.com/questions/4640011/append-text-to-file-from-command-line-without-using-io-redirection

其實最簡單的就是
$ export lines="text you want to append"
$ echo $lines >> file
$ echo "" >> file



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
============================================



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


============================================

If lines="a\nb", then echo -e "a\n${lines}\n.\nwq" | ed filetoedit will add
a
b
at the end of file.
EDIT: in fact there is an IO redirection. But perhaps it could help others.

沒有留言:

張貼留言