shell script help
I am creating a new script, sub2, taking three parameters, that treats the string to be replaced as plain text instead of as a regular expression.
The script works for everything except spaces. #!/bin/csh set firstString="$1" set secondString="$2" set file="$3" #adds on escape characters to be used later in sed set arg=`echo "$firstString" | sed 's:[]\[\^\$\.\*\/]:\\&:g'` sed "s/$arg/$secondString/g" "$file" > "$file.updated" mv "$file.updated" "$file" from my terminal here are a few examples: sub2 o a test.txt test.txt will change from "hello world" to "hella warld" sub2 . ! test.txt "hello..." to "hello!!!" my problem is I do not understand much about shell scripting or sed in general. when i type : sub " " x test.txt I expect all the spaces to be replaced with "x". But I get an error: sed: -e expression #1, char 0: no previous regular expression Any help would be greatly appreciated. |
Hi there,
Maybe you should use sed with a -e option: Code:
sed -e "s/$arg/$secondString/g" "$file" > "$file.updated" EDIT: 1.- can you post the value of $arg? 2.- Shouldn't you escape secondString too? At least for slashes and variables... |
sed -e "s/$arg/$secondString/g" "$file" > "$file.updated"
with echo "$firstString" echo "$secondString" echo "$file" echo "$arg" this was the output: sub2 " " a test1.txt (command I ran from the terminal) spaces indicate the values firstString and secondString a test1.txt sed: -e expression #1, char 0: no previous regular expression So still not there yet. If I eventually figure it out ill post on here what I was missing. |
Hi again,
What about using bash instead of csh? Code:
#!/bin/bash |
I am using ssh to connect to the linux box. So I don't think I have that option. It should work on either but I'm not sure. Why I am posting on the newbie forum.
|
Hi again,
Sorry, I don't know nearly anything about csh. I know it's doing some substitutions differently from what bash does (it strips initial/final spaces, for example). To use bash in your script instead of csh you only need to change csh to bash in the hash bang (#!/bin/bash, script's first line). Then, you can stop using 'set' and you can use $(command) instead of `command`. The example I posted before works as expected if bash is installed in the system (nearly all modern linux have it installed). |
I tried what you suggested and it isn't working on cases that previously were. Would you please post what you got working so I know that I changed everything properly.
|
I switched it over to sh correctly. Now the expression arg="`echo "$firstString" | sed 's:[]\[\^\$\.\*\/]:\\&:g'`" isnt returning the proper variable.
What is a good expression to change special characters to special characters with escape characters. For example * to \* etc |
Maybe [:punct:]?
|
All times are GMT -5. The time now is 06:19 AM. |