Making a shell script

May 3, 2010 at 09:59:26
Specs: Windows Vista
I am trying to wrtie a script in UNIX and am having some trouble with the string substitution. Here is what I have so far..

#!/bin/csh
set p1=$1
shift
set p2=$1
shift
foreach x ($*)
if ( { grep -w -c $p1 $x } ) then
mv $x $x.bak
sed "s/$p1/$p2/g" $x.bak > $x
else
endif
end

I am having trouble if the target($p1) or replacement(p$2) is a string like "hello everyone", which includes spaces. I know this is a simple solution, but its been driving me bonkers and I just can't figure it out or remember it. Thanks for any help.


See More: Making a shell script

Report •

#1
May 3, 2010 at 11:37:44
Try using double quotes around your argument:

#!/bin/csh

set p1="$1"
echo "$p1"


Report •

#2
May 3, 2010 at 12:09:41
That was it!, thanks alot.

Now the only thing left I can't figure out is how to make this script work for multiple files, say I wanted to make a replacement on any number of files.


Report •

#3
May 3, 2010 at 19:11:53
One way is to set up a while loop to process the command line arguments. Shifting the command line decreases the number of command line arguments, $#argv. When $#argv equals 0, stop the loop:

#!/bin/csh

while (1)
   set p1=$1
   shift
   set p2=$1
   shift
   # break if the number of arguments equal zero
   if ( $#argv == 0 ) then
      break
   endif
   foreach x($p1 $p2)
     echo "$p1"
     echo "$p2"
   end
end


Report •

Related Solutions

#4
May 5, 2010 at 22:08:58
I couldn't get that too work, any other way to implement that into my original code?

Report •

Ask Question