Why sed didn’t work in my bash script?

Here is my code. I just want to copy some files and replace the line in my Makefile. The $ 1 parameter 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 have the following error: sed: 1: "'s/mon.tex/salut.tex/g'": invalid command code '

ps: I use sed on Mac OS X. (so is bsd sed)

+5
source share
4 answers

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

Removing single quotes will solve this problem, but redirecting ( >) will still not work.

Just run the sed command directly (what a variable point $sed, I don't understand it)

. sed, sed -i. , , .

+6

' ( ).
' sed.

:

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

eval Quote Removal :

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

:

  • >Makefile Makefile ! Makefile.new.
  • eval - . sed !
0

sed:

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

sed. :

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

:

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

a >

, , ... , .

0

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

Which creates a variable sedcontaining a string sed 's/mon.text/foo.tex/g', assuming it $1is foofor example.

Then you expand $sedwithout quotes and become

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

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

sed -e \''s///' 

EDIT: I repeat, your problem is that you are unnecessarily quoting an expression sedinside a variable's destination. Use

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

And it will work as expected.

0
source

All Articles