Linux 在不使用 io 重定向的情况下从命令行将文本附加到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4640011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append text to file from command line without using io redirection
提问by apoorv020
How can we append text in a file via a one-line command without using io redirection?
我们如何在不使用 io 重定向的情况下通过单行命令在文件中附加文本?
采纳答案by taskinoor
If you don't mind using sedthen,
如果你不介意使用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$
is used to specify the last linea
means append a line after\
is simply used as a delimiter
-i
表示就地转换,因此所有更改都将发生在您指定的文件中$
用于指定最后一行a
意味着在后面添加一行\
仅用作分隔符
回答by Joel Berger
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"); 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".
注意,虽然>>
看起来像是重定向的指示,但它只是文件打开模式,在这种情况下是“附加”。
回答by Steven Penny
You can use Vim in Ex mode:
你可以在 Ex 模式下使用 Vim:
ex -sc 'a|BRAVO' -cx file
a
append textx
save and close
a
附加文本x
保存并关闭
回答by Ondra ?i?ka
You can use the --append
feature of tee
:
您可以使用以下--append
功能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
.
我假设不重定向的请求 ( >>
) 来自需要在xargs
或类似的情况下使用它。因此,如果这不算数,您可以使用>/dev/null
.