-1
port.properties
{
  "port":3006
  "name":"John"
}

changeport.sh

filename="port.properties"
oldport=$(awk -F'"port":|,' '{i=$2;print i}'  "$filename")
read newport
oldport_str="\"port\":$oldport"
newport_str="\"port\":$newport"

sed -i "s/$oldport_str/$newport_str/g" "$filename"

I don't know about the error.If you have the answer,please tell me,thanks

3
  • On line 1, character 7, the "s" command is unterminated. I don't even know the language, but the error message is quite self-explanatory. I'll bet I could fix the syntax problem with a few seconds of effort. Have you tried? Aug 30, 2014 at 3:27
  • i think it's beacuse of the quotes which was present inside your variable. Aug 30, 2014 at 3:28
  • The problem is from "old-port" the variable which is read from port.properties,if I just set the "old-port" value in the script or input by command,that's right.Is there different from them?
    – JohnKery
    Aug 30, 2014 at 3:49

2 Answers 2

1

Something in the old value is off; it contains an invisible character (DOS carriage return?) or something you are not showing us.

Anyway, finding the old value using a regex just so you can replace it is not preventing any accidents here, so the simplest fix is to remove the part which reads the old value.

read newport
sed -i "s/\(\"port\":\).*/\1$newport/" port.properties

Some sed dialects do not require backslashes before capturing parentheses; experiment with the precise syntax for your version before committing anything.

1
  • The |, part of your Awk script's -F argument suggests that maybe you are not really showing us precisely what the input file looks like. If it's different in reality, you'll obviously have to adapt the solution.
    – tripleee
    Aug 30, 2014 at 6:45
1

just change the whole thing to a simple:

filename="port.properties"
read -r newport
awk -v new="$newport" 'BEGIN{FS=OFS=":"} $1~/"port"/{$2=new} 1' "$filename" > tmp &&
mv tmp "$filename"

The above will work no matter what characters are in your file or read input string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.