首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用here-string追加或写入文件

使用here-string追加或写入文件
EN

Stack Overflow用户
提问于 2017-08-15 05:59:05
回答 1查看 313关注 0票数 1

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

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

代码语言:javascript
复制
ed fileName <<< $'a textToWriteInFile\nwq'

前面的代码行不起作用,尽管我已经阅读了一些ed手册页,但我仍然对here-strings方法感到困惑。我对here-document方法不感兴趣。

我尝试了带有H选项的ed H myFile <<< $'a\nMy line here\n.\nwq',得到了错误

代码语言:javascript
复制
H: No such file or directory

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

EN

回答 1

Stack Overflow用户

发布于 2017-08-15 06:20:53

tl;dr:

代码语言:javascript
复制
ed myFile <<< $'a\nMy line here\n.\nwq'

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

因此,第一步是查看如何在ed中追加行。这是info ed

下面的示例会话演示了使用'ed‘编辑行的一些基本概念。我们从创建一个文件开始,在莎士比亚的帮助下,创建了一个名为“十四行诗”的文件。与shell一样,“ed”的所有输入都必须后跟一个字符。注释以“#”开头。

代码语言:javascript
复制
 $ 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

好的,现在让我们调整一下,将一行附加到文件中,然后退出:

代码语言:javascript
复制
$ touch myFile
$ ed myFile
a
Some text here
.
wq

让我们验证一下它是否起作用:

代码语言:javascript
复制
$ cat myFile
Some text here

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

代码语言:javascript
复制
$ cat <<< $'a\nMy line here\n.\nwq'
a
My line here
.
wq

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

代码语言:javascript
复制
$ echo "Existing contents" > myFile
$ ed myFile <<< $'a\nMy line here\n.\nwq'
18
31
$ cat myFile
Existing contents
My line here
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45683660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档