1

我想替换路径

(setq myFile "/some/path")

在一个文件中。我试着用 sed 来做:

find ./_build/html -type f -name '*.html' | while read myFile; do
    MyFile=`readlink -f "$myFile"`
    sed -i "s/setq myFile [)]*/setq myFile \"$MyFile\"/" sphinx_nowrap.el
    # and then some actions on file
done

并使用 perl:

find ./_build/html -type f -name '*.html' | while read myFile; do
    MyFile=`readlink -f "$myFile"`
    perl -ne "s/setq myFile .+/setq myFile \"$MyFile\")/" sphinx_nowrap.el
    # and then some actions on file
done

但两者都给出错误。

我读过这个这个还有这个——但不能让它工作。

编辑

这是一个 perl 错误:

Having no space between pattern and following word is deprecated at -e line 1.
Bareword found where operator expected at -e line 1, near "s/setq myFile .+/setq myFile "/home"
String found where operator expected at -e line 1, at end of line
        (Missing semicolon on previous line?)
syntax error at -e line 1, near "s/setq myFile .+/setq myFile "/home"
Can't find string terminator '"' anywhere before EOF at -e line 1.

这是 sed 错误:

sed: -e expression #1, char 34: unknown option to `s'

编辑 2

所以解决方案是更改分隔符字符。并且 sed 表达式也应该改变:

sed -i "s!setq myFile .*!setq myFile \"$MyFile\")!" sphinx_nowrap.el
4

2 回答 2

4

看起来 perl(和 sed)将文件路径中的斜杠识别为正则表达式分隔符。您可以使用不同的分隔符:

find ./_build/html -type f -name '*.html' | while read myFile; do
    MyFile=`readlink -f "$myFile"`
    perl -ne "s!setq myFile .+!setq myFile \"$MyFile\")!" sphinx_nowrap.el
    # and then some actions on file
done

或者对于 sed:

find ./_build/html -type f -name '*.html' | while read myFile; do
    MyFile=`readlink -f "$myFile"`
    sed -i "s!setq myFile [)]*!setq myFile \"$MyFile\"!" sphinx_nowrap.el
    # and then some actions on file
done
于 2012-08-27T12:08:15.550 回答
2

让我们假设你$MyPath持有/foo/bar/baz。然后 Perl 代码如下:

perl -ne "s/setq myFile .+/setq myFile \"/foo/bar/baz\")/" sphinx_nowrap.el

您的正则表达式以第三个/字符终止。为了解决这个问题,我们可以使用另一个分隔符,例如s{}{}

perl -ine "s{setq myFile .+}{setq myFile \"/foo/bar/baz\")}; print" sphinx_nowrap.el

我还添加了-i选项(就地编辑)和一个print语句,以便实际打印出来。

$MyPath但是将值 aof作为命令行参数传递可能会更优雅:

perl -ne 's{setq myFile .+}{setq myFile "$ARGV[0]")}; print' $MyPath <sphinx_nowrap.el >sphinx_nowrap.el
于 2012-08-27T12:12:56.560 回答