Linux bash:在文件中搜索和替换,轻松无忧

Linux bash:在文件中搜索和替换,轻松无忧

是否有任何 bash 解决方案可以进行简单的“搜索和替换”而不逃避麻烦?我尝试<!-- JavaScript -->用复杂的 javascript 文件的内容替换 html 文件。

我努力了

JS=$(<"path to javascript file")
sed "s|<!-- JavaScript -->|${JS}|g" "path to html file" > "path to html file"

但只要得到

sed: -e Ausdruck #1, Zeichen 16: Nicht beendeter `s'-Befehl

在 Powershell 中我做

$CSS = Get-Content "path to javascript file"
(Get-Content "path to html file").replace('<!-- JavaScript -->', $JS) | Set-Content "path to html file" -Force

它就像一个魅力,没有逃避麻烦。

更新(但也不起作用):

JS=$(<"${TemporaryPath}/${Project}/${Project}.js")
E='!'
sed "s|<${E}-- JavaScript -->|${JS}|g" "path to html file" > "path to html file"

我明白了sed: -e Ausdruck #1, Zeichen 68: Nicht beendeter s'-Befehl。如果我将 $JS 的内容更改为“foo”之类的基本内容,它就可以工作。可能是 $JS 的 javascript 内容有问题?我该怎么办才能使 $JS 的内容无关紧要?

答案1

你的问题是 bash 正在解释感叹号。不幸的是,用反斜杠转义是行不通的。将其放在另一个变量中,或者将其放在单引号中,同时将变量放在双引号中,一切都会好起来的。 。 。

$ ARG="mytest"
$ echo "hello $ARG!"
bash: !": event not found
$ # didn't work
$ echo "hello $ARG\!"
hello mytest\!
$ # didn't work either!
$ echo "hello $ARG"'!'
hello mytest!
$ # that's better
$ E='!'
$ echo "hello $ARG$E"
hello mytest!
$ I like this one best.

答案2

使用单引号而不是双引号:

[alexus@wcmisdlin02 Downloads]$ test="testing"
[alexus@wcmisdlin02 Downloads]$ echo "$test"
testing
[alexus@wcmisdlin02 Downloads]$ echo '$test'
$test
[alexus@wcmisdlin02 Downloads]$ 

相关内容