Adobe
Adobe

Reputation: 13487

Substituting path

I want to replace path in

(setq myFile "/some/path")

in a file. I tried to do it with 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

and with 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

but both give errors.

I've read this and this and also this -- but can't make it work.

Edit:

Here's a perl error:

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.

and here's sed error:

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

Edit 2:

So the solution is to change the delimeter char. And also sed expression should be changed:

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

Upvotes: 2

Views: 4020

Answers (2)

amon
amon

Reputation: 57656

Lets assume your $MyPath hold /foo/bar/baz. Then the Perl code reads as:

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

Your Regex is terminated with the third / character. To work around this, we can use another delimiter like s{}{}:

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

I also added the -i Option (inplace editing) and a print statement so that something actually gets print out.

But probably it would be more elegant to pass the value aof $MyPath as a command line argument:

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

Upvotes: 2

perreal
perreal

Reputation: 98118

Looks like perl (and sed) recognizes the slash in the file path as the regex delimiter. You can use a different delimiter:

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

or for 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

Upvotes: 4

Related Questions