0

I have a bash script, replace.sh with the following contents:

ack-grep -a -l -i --print0 --text "$1" | xargs -0 -n 1 sed -i -e 's/$1/$2/g'

When I try and run it as, eg:

replace.sh something somethingnew

The prompt returns without errors but no changes have been made to any files. If I manually type:

ack-grep -a -l -i --print0 --text "something" | xargs -0 -n 1 sed -i -e 's/something/somethingelse/g'

The files get changed as expected.

Ths $1 syntax seems to work for other scripts I've written. I'm guessing I'm missing something to do with escaping the args or something?

Thanks!

Ludo.

Ludo
  • 2,739
  • 2
  • 28
  • 42

3 Answers3

4

Variable substitutions aren't done in single quotes, try:

ack-grep -a -l -i --print0 --text "$1" | xargs -0 -n 1 sed -i -e "s/$1/$2/g"

See the bash man page section on QUOTING.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
mrtimdog
  • 487
  • 4
  • 13
1

Use "" instead of '' in the sed expression. It will not prevent the variablename-resolving. What you are actually doing now is replacing $1 to $2. You can test in console (without writing a script) like this:

$ a=something

$ b=somethingelse

$ sed 's/$a/$b/g' testfile

$ sed "s/$a/$b/g" testfile
alain.janinm
  • 19,951
  • 10
  • 65
  • 112
Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
  • Thanks! :) 2 x correct answers, both at the same time, but gave the answer to the other bloke as it was his first answer. Thanks :) – Ludo Mar 02 '12 at 16:12
0

This isn't related to your question, but some help on using ack.

The -a and --text conflict with each other. -a will give you a superset of --text. Use one or the other.

Also, it looks like you might as well use grep -Z instead of ack since you're not using any of ack's functionality that is a superset of grep.

In general, if you're using ack in a pipeline, you should probably be using good ol' grep instead.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152