【问题标题】:How to replicate VSCode's 'search and replace' code in Bash?如何在 Bash 中复制 VSCode 的“搜索和替换”代码?
【发布时间】:2022-09-23 04:24:15
【问题描述】:

我有一个项目,其中包含一个文件a.txt,其中包含文本hello,以及一个名为b 的文件夹,其中包含一个文件c.txt,其中还包含文本hello。我想运行一个 bash 命令,将 hello 的这两个实例替换为 goodbye,与 VSCode 的搜索和替换功能相同。

我试过sed -i \'.bak\' \'s/hello/goodbye/g\' *,但它给了我错误sed: folder: in-place editing only works for regular files

我应该如何处理这个?我正在使用 MacOS。

  • 错误消息告诉您* 匹配的内容比您告诉我们的文件更多,可能是一个目录。投票结束作为不可复制/通用计算。

标签: macos sed


【解决方案1】:

您可以使用find 来定位您需要编辑的文件,并使用--exec 参数来运行您的sed 命令。就像是

find . -name '*.txt' -type f -exec sed -i '.bak' 's/hello/goodbye/g' {} \;

【讨论】:

  • 当我运行时,我得到find: --exec: unknown primary or operator
  • 对不起,我应该提到我使用的是 Mac。我已经更新了原始问题。
  • 它确实进行了替换,但它显示了以下两个输出:sed: .: in-place editing only works for regular filessed: ./folder: in-place editing only works for regular files,然后它为每个文件创建 .bak 备份文件。有没有办法防止这种情况?
  • 这里的想法是正确的,但是代码是错误的;它在通配符'*.txt' 之前缺少-name 谓词。可能在之前添加-type f,或者根据您的实际需要添加。
猜你喜欢
  • 1970-01-01
  • 2019-10-09
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 2010-10-30
  • 2017-01-05
相关资源
最近更新 更多