Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of update lines in a file without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
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')
We are here to answer your question about update lines in a file - If you find the proper solution, please don't forgot to share this with your team members.