gpt4 book ai didi

bash - 用文件中的多行替换一行

转载 作者:行者123 更新时间:2023-11-29 08:57:21 32 4
gpt4 key购买 nike

我想用多行替换文件中的一行,例如,我想替换一个特定的函数调用,比如说,

foo(1,2)

if (a > 1) {  
foo(1,2)
} else {
bar(1,2)
}

我怎样才能在 bash 中做到这一点?

最佳答案

这就是 sed s 命令的用途:

shopt -s extglob

ORIG="foo(1,2)"
REP="if (a > 1) {
foo(1,2)
} else {
bar(1,2)
}"

REP="${REP//+(
)/\\n}"

sed "s/$ORIG/$REP/g" inputfile > outputfile

请注意,REP="${REP//\+( )/\\n}" 行仅在您想要定义 REP我在第二行所做的格式化方式。如果您只是在 REP 中使用 \n\t 开始,它可能会更简单。

编辑:注意!如果你有 REP,你还需要转义 '\

针对 OP 的问题进行编辑

要更改原始文件而不创建新文件,请使用 sed 的 --in-place 标志,如下所示:

sed --in-place "s/$ORIG/$REP/g" inputfile

请注意 --in-place 标志。在运行之前进行备份,因为所有更改都是永久性的。

关于bash - 用文件中的多行替换一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10576604/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com