Matthieu Riegler
Matthieu Riegler

Reputation: 54569

Why would sed not work in my bash script?

Here is my code. I simply want to copy some files and replace a line in my Makefile. The parameter $1 is just the name of my new .tex file.

#!/bin/bash                                
pwd="./"                                   
tex=".tex"                                 
pwd=$1$tex                                 
cp ~/TeX/matt.sty .                        
cp ~/TeX/mon.tex $pwd                      
cp ~/TeX/Makefile .                        

sed="sed 's/mon.tex/"$1$tex"/g' Makefile > Makefile"           
$sed

I've the following error : sed: 1: "'s/mon.tex/salut.tex/g'": invalid command code '

ps: i'm using sed on Mac OS X. (so it's bsd sed)

Upvotes: 4

Views: 3989

Answers (4)

kev
kev

Reputation: 161604

The error message is caused by the '(single quote).
And, the ' is not a valid sed command.

Example:

$ echo="echo 'hello, world'"
$ $echo
'hello, world'

You can use eval command to Quote Removal further more:

sed="sed 's/mon.tex/"$1$tex"/g' Makefile > Makefile.new"          
eval $sed

Note:

  1. >Makefile will make your orginal Makefile empty! So change it to Makefile.new.
  2. eval is evil. Try to use sed directly!

Upvotes: 0

sorpigal
sorpigal

Reputation: 26086

You say

sed="sed 's/mon.tex/"$1$tex"/g'"  

Which creates a variable sed containing the string sed 's/mon.text/foo.tex/g', presuming that $1 is foo for the sake of example.

You then expand $sed unquoted and it becomes

sed ''\''s/mon.tex/foo.tex/g'\'''

Which includes a literal ' at the beginning of your expression, as if you had said:

sed -e \''s///' 

EDIT: To reiterate, your problem is that you're needlessly quoting your sed expression inside the variable assignment. Use

sed="sed s/mon.tex/$1$tex/g Makefile > Makefile"

And it will work as expected.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

The first argument to sed is literally 's/mon.tex/"$1$tex"/g' (with single quotes). obviously sed cannot parse that as a command.

Removing the single quotes would solve that problem but redirection (>) still won't work.

Just run the sed command directly (what's the point of the $sed variable? i don't get it)

Note: to modify a file with sed, use sed -i. Redirecting to the same file you are processing won't work.

Upvotes: 5

Marc B
Marc B

Reputation: 360562

You've doubling up your sed command line:

sed="sed 's/mon.tex/"$1$tex"/g'"           

creates a sed variable. You then use this variable as a command:

$sed s/mon.tex$1$tex/g Makefile > Makefile     
^^^^---here

which effectively makes your command line:

sed 's/mon.tex/"$1$tex"/g' s/mon.tex$1$tex/g Makefile > Makefile
^^^^^^^^^^^^^^^^^^^^^^^^^^--var   
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- excess args

and now I see your question's been editted to remove that... so ignore this, I guess.

Upvotes: 0

Related Questions