2017-08-14 58 views
1

如何使用ed编写文件或将文件追加到文件中?使用here-strings追加或写入文件

我有其他编辑的知识,但在编一个bash脚本编写的这种特殊形式混淆了我很多:

ed fileName <<< $'a textToWriteInFile\nwq' 

前一行不起作用,虽然我看过一些编手册页,我仍然与here-strings方法混淆。我对here-document方法不感兴趣。

编辑:

我试过$ ED^h MYFILE < < < $ '一\ n我行这里\ n \ nwq' 与H选项和我得到的错误“H:没有这样的文件或目录'。我已经创建了一个名为myFile的文件,并在我的目录中创建了一个名为chmod a + wx myFile的文件。

+0

您是否需要编辑器? 'echo'textToWriteInFile \ nwq'>> fileName'会工作.. –

回答

4

TL;博士:

ed myFile <<< $'a\nMy line here\n.\nwq' 

一个可悲的事实有关编程,你永远无法自动什么,你不知道该怎么做手工。如果您不知道如何手动在ed附加一行,则无法通过ed和here字符串自动追加行。

因此,第一步是查找如何在ed附加行。这里的info ed:下面

样本会话来解释线 与“编”编辑的一些基本概念。我们首先创建一个文件,'sonnet',其中有一些来自莎士比亚的帮助 。和shell一样,'ed'的所有输入都必须是 后跟一个字符。评论以'#'开头。

$ ed 
# The 'a' command is for appending text to the editor buffer. 
a 
No more be grieved at that which thou hast done. 
Roses have thorns, and filvers foutians mud. 
Clouds and eclipses stain both moon and sun, 
And loathsome canker lives in sweetest bud. 
. 
# Entering a single period on a line returns 'ed' to command mode. 
# Now write the buffer to the file 'sonnet' and quit: 
w sonnet 
183 
# 'ed' reports the number of characters written. 
q 

好了,现在让我们来适应,要一行追加到一个文件,然后退出:

$ touch myFile 
$ ed myFile 
a 
Some text here 
. 
wq 

并让我们验证它的工作:

$ cat myFile 
Some text here 

耶。现在我们可以手动追加一行,我们只需要用here字符串重新创建相同的输入。我们可以用cat来验证我们的输入是正确的:

$ cat <<< $'a\nMy line here\n.\nwq' 
a 
My line here 
. 
wq 

啊,这正是我们所使用的输入。现在我们可以将其插入ed

$ echo "Existing contents" > myFile 
$ ed myFile <<< $'a\nMy line here\n.\nwq' 
18 
31 
$ cat myFile 
Existing contents 
My line here