Domanda

I would like to concatenate strings together to create a command string in a csh script,file1.csh. However, csh keeps complaining errors for commandString variable and I do not really know what I did wrong. Here are part of codes.

set var1 = "Hat"
set var2 = 100
set embeddedString = 's/'$var1' =.*$/'$var1' = '$var2'/g'
set commandString = "sed -i ' "$embeddedString" ' productPrice.txt"
echo $commandString

My goal is to set commandString vairable to be something as

sed -i 's/Hat =.*$ /Hat = 100/g' productPrice.txt 

Then, this commandString will be inserted into another script file,file2.csh. file2.csh is the actual script file which performs the substitution command for Hat's price. In addition, the values of var1 and var2 are read from a priceUpdateList.txt file so they are not fixed values. On other words, I can not simply type Hat and 100 in the commandString variable. Does anyone know how to use quotation correctly to generate the command string in csh ?

Thank you so very much,

È stato utile?

Soluzione

You'll have to quote (at least 1x) the embedded single-quotes (i.e. cmdStr = "sed -i \' .... To actually run the $cmdStr you're going to need eval right?

To use shell debugging in csh (which I would recommend to see what is happening), change the first line in your script to

#!/bin/csh -vx

This will show you each line or block of code as it is executed, and then the same block of code with the environment variables expanded.

Altri suggerimenti

how about: set embeddedString="s,$var1 =.*,$var1 = $var2,g" set commandString="sed -i '$embeddedString' productPrice.txt"

you can use / instead of , in embeddedString if you want :-)

Sorry I forgot to explain the No Match quoted by Cassie The difference between

 echo $commandString

andenter code hereecho "$commandString"

is that the first one echoes the result of the correctly built command (No match of course because it needs to read an absent file `named productPrice.txt , while the second, embedding the command in double quotes, shows the command itself, which is what was asked for.

Exceedingly simple:
Your goal is to set commandString variable to be something as

sed -i 's/Hat =.*$ /Hat = 100/g' productPrice.txt 

The below does it, and prints commandString for comparison with your goal...

Additionally all your quotes are useless save those which delimit your "final" strings.
But mostly, please note the missing space between .*$ and /$var1 . Enough to fool the interpreter which saw a string named $/ while string names ought to begin with a letter.

set var1 = "Hat"
set var2 = 100
set embeddedString = "s/$var1 =.*$ /$var1 = $var2/g"
set commandString  = "sed -i $embeddedString  productPrice.txt"
echo  "$commandString"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top