Passing output of sed/echo to a variable

I understand how to use a variable in a sed command, but for the life of me I can't get the output into a variable.
I'm making a general function to replace part of a filename with a different string, so:
>>myscript this that

would change:
this_file001.txt to that_file001.txt and
this_file002.txt to that_file002.txt and so on...

here's what I have:
#! /bin/csh -f
foreach i ($1*)
set j = echo $i|sed 's/'$1'/'$2'/'
echo "Moving $i to $j"
#mv $i $j
end

But it gives me a syntax error. I played around with using eval but that wouldn't work for me either. Suggestions? (preferably without taking a new approach to my problem even though I'm sure there are other/better ways to do it)
Thanks....

Try this.

The changes are in bold.

#! /bin/csh -f
foreach i ($1*)
j=$(echo $i|sed 's/"$1"/"$2"/')
echo "Moving $i to $j"
#mv $i $j
end

Vino

Still giving me a "Variable Syntax" Error.

Can you post the whole error (variable syntax) that is thrown at the prompt ?

vino

This should get you going....

% set foo = "hello"
% set bar = "goodbye"
% set i = "I say hello to you all"
% set j = `echo "$i" | sed "s/$foo/$bar/"`
% echo $j
I say goodbye to you all

So, change your sed line to

set j = `echo "$i" | sed "s/$1/$2/"`

Cheers
ZB

I'm a tyro when it comes to cshells - all I'm getting is the output "Variable Syntax" to the command line. Is there a way to get more info from csh?

zazzybob:
That will set j to be `echo "$i" | sed "s/$1/$2/"` not actually execute the command.
When I run my script it wants to rename this_file001.txt to echo "$i" | sed "s/$1/$2/"

No it won't.

Have you tried it?

That code was for tcsh but from the csh manual page you'll see that backticks are used for Command Substitution. As I sit here using tcsh day after day at work I think I know what this assignment will do....

Cheers
ZB

ZB-
Sorry I didn't mean to imply you didn't know what you're talking about, but I did try it and it is not working as expected. If I do an echo $j it will spit out
echo "$i" | sed "s/$1/$2/"

Is it possible that I have something set that is different from what you are running?

No probs :wink:

I think I see the problem....

I didn't use code tags and maybe the backticks look like single quotes if you haven't copied and pasted directly....

set j = `echo "$i" | sed "s/$1/$2/"`

Cheers
ZB

:stuck_out_tongue: Duh

Ok, yes I am not cutting and pasting, I have am on my PC now but the code is on my UNIX box. As I said before, I only write these things when I need them so I had no idea that ' is different from `

Works Great! Thanks again, now I know... and knowing is half the battle.