2

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
Community
  • 1
  • 1
Adobe
  • 12,967
  • 10
  • 85
  • 126

2 Answers2

5

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
perreal
  • 94,503
  • 21
  • 155
  • 181
2

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
amon
  • 57,091
  • 2
  • 89
  • 149