将文本附加到命令行,而不使用io重定向。

时间:2022-04-18 23:59:19

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

如何在不使用io重定向的情况下,通过单行命令在文件中附加文本?

3 个解决方案

#1


58  

If you don't mind using sed then,

如果你不介意使用sed,

$ 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
  • -我的意思是一个inplace转换,所以所有的更改都会发生在您指定的文件中。
  • $ is used to specify the last line
  • $用于指定最后一行
  • a means append a line after
  • a表示后面的一行。
  • \ is simply used as a delimiter
  • \被简单地用作分隔符。

#2


5  

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):

如果您只是想手工添加一些东西,那么sed答案将适合您。如果文本在文件中(如file1)。txt和file2.txt):

Using Perl:

使用Perl:

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

perl -e 'open(OUT,“>>”,“outfile.txt”);打印时(<>);' file*.txt

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

>>可能看起来像是重定向的指示,但它只是文件打开模式,在这种情况下是“append”。

#3


2  

You can use Vim in Ex mode:

你可以在Ex模式下使用Vim:

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

    附加的文本

  2. x save and close

    x保存并关闭

#1


58  

If you don't mind using sed then,

如果你不介意使用sed,

$ 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
  • -我的意思是一个inplace转换,所以所有的更改都会发生在您指定的文件中。
  • $ is used to specify the last line
  • $用于指定最后一行
  • a means append a line after
  • a表示后面的一行。
  • \ is simply used as a delimiter
  • \被简单地用作分隔符。

#2


5  

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):

如果您只是想手工添加一些东西,那么sed答案将适合您。如果文本在文件中(如file1)。txt和file2.txt):

Using Perl:

使用Perl:

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

perl -e 'open(OUT,“>>”,“outfile.txt”);打印时(<>);' file*.txt

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

>>可能看起来像是重定向的指示,但它只是文件打开模式,在这种情况下是“append”。

#3


2  

You can use Vim in Ex mode:

你可以在Ex模式下使用Vim:

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

    附加的文本

  2. x save and close

    x保存并关闭