如何仅使用ed写入文件或将字符串附加到文件?
我了解其他编辑器,但是使用ed编写bash脚本的这种特殊形式让我很困惑:
ed fileName <<< $'a textToWriteInFile\nwq'前面的代码行不起作用,尽管我已经阅读了一些ed手册页,但我仍然对here-strings方法感到困惑。我对here-document方法不感兴趣。
我尝试了带有H选项的ed H myFile <<< $'a\nMy line here\n.\nwq',得到了错误
H: No such file or directory我已经创建了一个名为myFile的文件,并在我的目录中执行了sudo chmod a+wx myFile。
发布于 2017-08-15 06:20:53
tl;dr:
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 herehttps://stackoverflow.com/questions/45683660
复制相似问题