I want to use sed
in a script to modify the content of an existing file. I have a line like this…
sed -i '' 's/${scripts}/${newScripts}/' "$packpath"
… which does not do what I thought it would do on my Mac. I would appreciate any help you can give to correct this line.
On my Mac, I have created a script at ~/.zshrc
which contains the lines:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
I have a script at ~/.bash_aliases
which contains a number of aliases and functions to handle common tasks.
I often create small React projects that I want to deploy to GitHub, using the gh-pages
Node module. One step in this process is adding two lines to a file called package.json
.
For simplicity, let’s say that the package.json
file looks like this, before adding any lines.
{
"name": "react-project",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
After, it should look like this:
{
"name": "react-project",
"scripts": {
"dev": "vite",
"build": "vite build",
"predeploy": "npm run build",
"deploy" : "gh-pages -d dist"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
The function that I have added to my .bash_aliases
currently looks like this:
ghdeploy() {
package="package.json"
packpath="$PWD/$package"
packtext=`cat $packpath`
deploy_it=",\n "predeploy": "npm run build",\n "deploy" : "gh-pages -d dist"n "
setopt local_options BASH_REMATCH
regex='"scripts":[^}]+'
if [[ "$packtext" =~ "$regex" ]]; then
scripts=$BASH_REMATCH[1] ## includes final nss
if [[ "$scripts" =~ ("deploy": "w+") ]]; then
echo "package.json already contains deploy script"
else
chunk=${scripts:0:-3} ## remove final nss
newScripts="$chunk$deploy_it"
echo "newScripts: $newScripts"
sed -i '' 's/${scripts}/${newScripts}/' "$packpath"
fi
else
echo "scripts not found"
fi
}
The line echo "newScripts...
prints out the change that I want to make, but the line sed -i '' ...
does not apply those changes to my file.
What is it that I have failed to understand?