如何在 bash 函数中运行 `find -exec` --- 转义字符和文件意外结束的问题

ale*_*lec 2 bash sed find

我想让运行这种命令更容易:

find . -type f -exec sed -i 's|wpp-splash|wpp_splash|g' {} \;
Run Code Online (Sandbox Code Playgroud)

所以我在 my 中创建了一个函数.bashrc来缩短它:

function sedall() { find . -type f -exec sed -i 's|$1|g' {} \; }
Run Code Online (Sandbox Code Playgroud)

这样我可以做到

sedall wpp-splash|wpp_splash
Run Code Online (Sandbox Code Playgroud)

但是有一个语法错误。我不确定它是什么,但是该 bash 函数导致“文件意外结束”。我想知道是不是和}人物有关?我试图逃避他们,\{\}但这并没有解决问题。

请问有什么帮助吗?

Qua*_*odo 6

那里有很多问题。

  • 变量不会在单引号内展开。
  • { command ; } 需要终止分号(或换行符)。
  • sedall wpp-splash|wpp_splash 这被理解为管道,因为您没有用引号保护管道字符。

我建议这样做:

sedall(){
    [ "$#" = 2 ] || { echo Two arguments needed; return 9; }
    find . -type f -exec sed -i "s|$1|$2|g" {} \;
}
Run Code Online (Sandbox Code Playgroud)

它需要两个参数而不是一个,并检查这两个参数是否在执行前给出。

$ cat a b
XABCX
YABCY
$ sedall ABC DEF
$ cat a b
XDEFX
YDEFY
Run Code Online (Sandbox Code Playgroud)