简体   繁体   中英

Bash script: How to replace text in package.json with sed

I just wann write a very basic script, which

  • inits npm in a new project folder
  • Installs nodemon
  • creates an index.js file
  • adds a start command into the package.json for nodemon
  • writes "console.log" into the index.js file

I seem to be close, but adjusting the package.json does not work. Somehow the search variable is two time in ...

I want to achive:

"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"

I achive:

"test": "echo \"Error: no test specified\" "test": "echo \"Error: no test specified\" && exit 1""test": "echo \"Error: no test specified\" && exit 1" exit 1","start": "nodemon my_file.js"

Full code

#!/bin/bash -e
set -e
clear

# Init npm
npm init -y && npm i --save-dev nodemon && touch index.js

wait

# find test command
constToFind='\"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"'

# add nodemon command (with comma, line break and tab)
replacement=',\n\t\"start\": \"nodemon my_file.js\"'
combineReplacement="${constToFind}${replacement}"

# Add start command to package.json
sed -i "s/$constToFind/$combineReplacement/g" package.json

# Create entry javascript file with console.clear on tops
echo "console.clear();" >> index.js

Instead of substituting you can append with the sed a command:

$ addon='\"start\": \"nodemon my_file.js\"'
$ sed "/$constToFind/a\
$addon
" package.json
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"

(if you care your package.json file use the -i only after you checked that it really works as expected).

And if your sed version supports the alternate syntax this is a bit simpler:

$ addon='\"start\": \"nodemon my_file.js\"'
$ sed "/$constToFind/a$addon" package.json
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon my_file.js"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM