update lines in a file

I have a file,where it has some fields.For example,

var One = "fcb";
var Two = "abc";

How can I update/replace these lines using a script?

I want to be able to do something like :

   echo -n "Enter One: "
   read  One
   echo -n "Enter Two: "
   read  Two

   sed -i $One ./file.js
   sed -i $Two ./file.js

But, when I execute the script:

Enter One: fge3
Enter Two: ghj5

it shows:

sed: -e expression #1, char 1: unknown command: `f'
sed: -e expression #1, char 2: extra characters after command

Answer

The sed command would look something like

sed -i -e 's/var One =.*/var One = "'$One'";/' -e 's/var Two =.*/var Two = "'$Two'";/' file.js

Edit to add:

Beware of a gotcha… if the user enters nasty characters like foo/bar as the answer 🙂

2nd Edit:

If you don’t want to allow the bad character then you can abort eg after the read One you can add:

if [[ "$One" =~ "/" ]]; then echo bad char / not allowed; exit; fi

You could pick a different character instead for the sed statement (e.g. a | instead of /) and disallow that.

Otherwise you’ll need to try some clever quoting…

One=$(echo "$One" | sed 's///\//g')

Leave a Reply

Your email address will not be published. Required fields are marked *