Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

sed works from the command line, but does not work if put it in an sh file and execute it. I want to change a number in an existing file and direct it to a new file, so I tried this:

echo enter number 
read num
var1='more ods2.sql | egrep -e "test" | cut -c 5-7' 
sed "s/test$var1/test$num/g" ods2.sql > odstest.sql

If I execute these statements in a prompt they execute with the desired results. I replaced $var1 with the string I passed, e.g 12345:

sed "s/test$var1/test$num/g" ods2.sql > odstest.sql

This also works fine from a prompt:

more ods2.sql | egrep -e "test" | cut -c 5-7'

Why isn't it working if I put this in a shell script?

share|improve this question

This line

var1='more ods2.sql | egrep -e "test" | cut -c 5-7'

should be

var1=`more ods2.sql | egrep -e "test" | cut -c 5-7`

i.e. you need to use backticks instead of single quotes (apostrophes).

share|improve this answer
or use $() which is easier to see, among other benefits. – glenn jackman Jun 4 '12 at 10:43
I'm not sure what more is supposed to be accomplishing either. Its probably best to remove it and have egrep read the file directly, or at the very least use cat instead. – Patrick Jun 5 '12 at 1:07

more is intended to work in a terminal. A simpler way is

var1=$(< ods2.sql grep "test" | cut -c 5-7)
sed "s/test$var1/test$num/g" ods2.sql > odstest.sql

Nit pick: be careful about that first line, though. You're making assumptions about the position and length of the text you want to extract from ods2.sql. I don't know what is var1 supposed to look like, but here's an example assuming it's a number:

var1=$(< ods2.sql sed -n 's/test\([:digit:]*\)/\1/p')
if ! [ -n "$var1" ]  # sed didn't find the pattern
    # complain, exit
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.