【问题标题】:write to a specific line in a file from a command line in MAC OS [duplicate]从MAC OS中的命令行写入文件中的特定行[重复]
【发布时间】:2020-04-29 15:47:59
【问题描述】:

我搜索了一下,在这个link找到了答案

但是当我尝试执行此命令sed -i '5ianything' file1.txt 时,它不起作用并显示错误消息:

sed: 1: "file1.txt": invalid command code f

当我使用另一个命令sed -i '5i\anything' file1.txt时也会出现同样的错误信息

我不知道为什么它对我不起作用我错过了什么吗? 有没有其他方法可以做到这一点?

编辑

我已经尝试了 cmets 中提供的解决方案并运行了这个命令,但不幸的是,即使这样也行不通

sed -i.bu '5i\anything' file1.txt
    sed: 1: "5i\anything": extra characters after \ at the end of i command  

这是我的 file1.txt :

1. alloha I want some cheese
2.
3. this is just a test and you know it
4. 
5. this line will change sooooo sooooooon
6. 
7. daaaamn, it changed I mean that line above me daaaaamn

编辑

在我在 sed 的 OSX 手册页中搜索了一下之后,我发现了这个:

-i extension
             Edit files in-place, saving backups with the specified extension.  If a zero-length extension is given, no backup will be saved.  It is not recommended
             to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

【问题讨论】:

  • 您使用的是最新版本的 gnu sed 吗? sed -V 说什么?
  • @match 实际上甚至 sed -V 在我的终端中也不起作用,并且我收到错误消息“sed:非法选项 -- V”我在 Mac 中工作
  • this 是您要找的吗?
  • @Chipster 不,即使那对我也不起作用
  • 您需要在 \ 之后换行

标签: bash macos shell sed command-line


【解决方案1】:

对于 BSD/Mac sed 提供就地替换的参数(-i 选项):

sed -i .bak '5i\
anything' file1.txt

或者在不创建备份的情况下替换原始文件,将空字符串传递给-i(您应该首先在没有-i 的情况下测试它并验证它是否按预期工作):

sed -i '' '5i\
anything' file1.txt

【讨论】:

  • 不幸的是,没有什么对我有用,我都试过了,同样的错误发生了:sed: 1: "5ianything": command i expects \ followed by text
  • 是的,现在在你添加了一个新行之后它工作得很好,你能给我推荐一个文件来解释为什么会在 mac 中发生这种情况。
  • GNU sed 记录在gnu.org/software/sed/manual/sed.html 中。 BSD sed 的手册页可以在 man.openbsd.org/sed 中找到(它不如 GNUs 文档全面)
猜你喜欢
  • 1970-01-01
  • 2016-08-01
  • 2015-03-21
  • 2023-03-23
  • 2015-03-20
  • 1970-01-01
  • 2011-12-11
  • 2015-05-23
  • 2013-06-29
相关资源
最近更新 更多