代替路径

时间:2012-08-27 11:57:32

标签: perl bash sed

我想替换

中的路径
(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

但两者都有错误。

我已阅读thisthis以及this - 但无法使其发挥作用。

修改

这是一个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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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语句,以便实际打印出来。

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

perl -ne 's{setq myFile .+}{setq myFile "$ARGV[0]")}; print' $MyPath <sphinx_nowrap.el >sphinx_nowrap.el