在 find -exec 的 sed 命令中使用文字空花括号 {}

mrb*_*nny 6 sed find

我不知道是否有可能包括空的大括号{}A内sed从一个叫做替代find -exec

一个例子:

find "$dir" -type f -name "*" -exec sed -i s/hello{}a/hello{}b/g '{}' +
Run Code Online (Sandbox Code Playgroud)

这带来了重复的错误消息{}

find: Only one instance of {} is supported with -exec ... +

有没有办法保留{}sed命令中并被视为文字,而不是替换找到的文件find

Bar*_* IO 7

在这种情况下,您可以find通过捕获大括号表达式并在替换文本中使用反向引用来解决exec 语法:

$ cat f1 f2
f1: hello{}a
f2: hello{}a
$ find . -type f -exec sed -i 's/hello\([{][}]\)a/hello\1b/g' '{}' +
$ cat f1 f2
f1: hello{}b
f2: hello{}b
Run Code Online (Sandbox Code Playgroud)

或者,更简单(如评论中所述):

find "$dir" -type f -exec sed -i 's/\(hello[{]}\)a/\1b/g' {} +
Run Code Online (Sandbox Code Playgroud)

请注意,-iSed的选项不可移植,并且不能在任何地方使用。给定的命令仅适用于 GNU Sed。

有关详细信息,请参阅: