Reputation: 728
I am trying to concatenate two strings from user input. These are "what to look for" and "what to replace" that text with. It will eventually be a part of a build process. I can't seem to get the variables to correctly concatenate. Here's the script:
#!/bin/bash
first=${1}
second=${2}
TO_REPLACE="Hello Kitties=$first"
REPLACEMENT="Hello Kitties=$second"
echo $TO_REPLACE
echo "s/${TO_REPLACE}/${REPLACEMENT}/g"
sed -i "s/${TO_REPLACE}/${REPLACEMENT}/g" "C:\\Test\\Mah.config"
I put the echo's in there to troubleshoot along with the first
and second
variable. The result I get is this:
mrhoden@mrhoden-dt ~
$ bash C:\\Users\\mrhoden\\workspace\\Test\\Concatenation.sh Yes No
Hello Kitties=Yes
/gello Kitties=Noes
I don't understand why the first one works fine, but not the second. I even considered the /
but when I replaced it with a l
or any other character I'm getting basically the same results. I've tried various ways of grouping the variables and escaping. I even downloaded and used eclipse with the ShellEd plugin in case there was some weird interaction between windows and unix based editors (previously Notepad++).
I'm at a loss, any help would be appreciated.
Upvotes: 1
Views: 2538
Reputation: 126013
Looks like your script file is in DOS/Windows format (with a carriage return followed by linefeed at the end of each line) rather than unix format (with just linefeed at the end of each line). When the shell executes it, it treats the carriage return (sometimes written \r
) as part of the command. For example: first=${1}\r
sets $first
to the first argument, with a carriage return appended. Then TO_REPLACE="Hello Kitties=$first"\r
sets $TO_REPLACE
to that, with another carriage return tacked on the end. So when you get to that second echo, what it's actually doing is:
echo "s/Hello Kitties=Yes\r\r/Hello Kitties=No\r\r/g"\r
When this prints, each carriage return makes the terminal go back to the beginning of the line, so it essentially prints three things, each on top of the last:
s/Hello Kitties=Yes
/Hello Kitties=No
/g
Leaving you with the combined mess:
/gello Kitties=Noes
Solution: as @shellter suggested, use dos2unix
to convert the script to unix format, and then stick to unix-style text editors for scripts.
Upvotes: 7