1

如何仅使用 ed 写入文件或将字符串附加到文件?

我了解其他编辑器,但这种用 ed 编写 bash 脚本的特殊形式让我很困惑:

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

上一行不起作用,虽然我已经阅读了一些 ed 手册页,但我仍然对该here-strings方法感到困惑。我对这种here-document方法不感兴趣。

我已尝试ed H myFile <<< $'a\nMy line here\n.\nwq'使用该H选项,但出现错误

H: No such file or directory

我已经在我的目录中创建了一个名为myFile并执行的文件sudo chmod a+wx myFile

4

1 回答 1

4

tl;博士:

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

关于编程的一个可悲的事实是,您永远无法自动化您不知道如何手动完成的任何事情。如果您不知道如何使用 手动追加一行ed,则不能希望通过ed和 here-string 自动追加一行。

因此,第一步是查找如何在ed. 这是info ed

下面的示例会话说明了使用“ed”进行行编辑的一些基本概念。我们首先在莎士比亚的帮助下创建一个文件“十四行诗”。与 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-string 重新创建相同的输入。我们可以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
于 2017-08-14T22:20:52.880 回答