-   Programming (
-   -   problems with variables using sed or awk in script (

FeatherKing 09-14-2008 10:02 PM

problems with variables using sed or awk in script
I am trying to compare the differences in two variables to make a third variable. Much like running 'diff file1 file2' i am trying to run

FILE3=`echo $FILE1 | sed -e "s/$FILE2//g"
this is working correctly if $FILE2 is something simple like a line of text.

The problem i am running into is: $FILE2, in my case, has a "." (for example two names: "john.larson kyle.hyde") in it and sed is trying to interpret the "." as a special character. I cant escape it because its inside the variable. Awk is giving the same behavior with something like

FILE3=`echo $FILE1 | awk -v FILE2=$FILE2 '{gsub(FILE2, "")'`
but it complains the the "." in the variable is a syntax error, and again i cant escape it becuase it is in a variable.

I have also tried something like

FILE3=`echo ${FILE1//FILE2/}`
and this doesnt seem to error at all but it is not actually removing the FILE2 information from FILE1.

Because of the functions later in the script, i need to keep the periods as they are. Right now i have this working by sending the command out to two text files and comparing them with diff. If possible i would like to do this in the script using only variables.

Mr. C. 09-14-2008 10:41 PM

You can use perl's \Q \E quoting characters to avoid special character interpretation.


$ FILE1='tom.foolery'; FILE2='tom.fool' ; echo $FILE1 | perl -pe "s/\Q$FILE2\E//"   

$ FILE1='tom foolery'; FILE2='tom.fool' ; echo $FILE1 | perl -pe "s/\Q$FILE2\E//"
tom foolery

FeatherKing 09-14-2008 11:48 PM

Unfortunatley this is a pretty basic load and perl is not part of it. I was looking at some examples of using & within gsub like

gsub(&FILE2, "")
but again it complains about syntax

Kenhelm 09-14-2008 11:51 PM

In Bash this removes every match of $FILE2 from $FILE1

You can also escape the '.' for sed.
Here ${FILE2//./\\.} replaces all '.' in $FILE2 with '\.'

FILE3=`echo "$FILE1" | sed -e "s/${FILE2//./\\.}//g"`

FeatherKing 09-15-2008 12:13 AM

Excellent, i guess i was just missing some double quotes, this worked great

FILE3=`echo ${FILE1//"FILE2"/}
Thanks again

All times are GMT -5. The time now is 06:20 PM.