Important:
I wrote this function to manipulate my
package.json
.
This is a suboptimal solution; the correct way is via the officialnpm-pkg
.
@nicholaswmin
MIT
#!/usr/bin/env | |
####################################### | |
# deleteJSONKey() $key $json_file_path | |
# | |
# Deletes a property from a JSON file, | |
# taking care of dangling commas if needed | |
# | |
# Usage example: | |
# | |
# deleteJSONKey "version" package.json | |
# | |
# Removes the "version" property | |
# of file "package.json"" | |
# | |
# Note: | |
# - Only the 1st match is removed. | |
# - To remove multiple instances of the same key, | |
# call it multiple times. | |
# | |
# Globals: | |
# | |
# - none | |
# | |
# Arguments: | |
# | |
# - key : the JSON key/property name to remove | |
# - file: the JSON file path | |
# | |
# Returns: | |
# | |
# - 0 if key was deleted | |
# - 1 otherwise | |
# | |
# License: MIT | |
# Authors: @nicholaswmin | |
####################################### | |
deleteJSONKey () { | |
local key=$1 | |
local file=$2 | |
# verify params | |
if ! [[ "${key}" ]]; then | |
echo "- Missing \"key\" parameter" | |
return 1 | |
fi | |
if ! [[ "${file}" ]]; then | |
echo "- Missing \"file\" parameter" | |
return 1 | |
fi | |
if [[ ! -f "${file}" ]]; then | |
echo "- File: $file does not exist" | |
return 1 | |
fi | |
local count=$(grep -n "${key}" "${file}" | wc -l) | |
local line_num=$(grep -n "${key}" "${file}" | head -1 | grep -Eo '^[^:]+') | |
if [[ -z "$line_num" ]]; then | |
echo "- Cannot find key: \"${1}\" in: ${file}" | |
return 1 | |
fi | |
# we also need the previous line in case it has | |
# a dangling comma | |
local line=$(sed -n "${line_num}"p "${file}") | |
local prev_line_num=$((line_num - 1)) | |
local prev_line=$(sed -n "${prev_line_num}"p "${file}") | |
# remove dangling comma of previous line, | |
# if we need to. | |
if ! [[ "${line: -1}" =~ ^[,]$ ]]; then | |
if [[ -n "$prev_line" ]] && [[ "${prev_line: -1}" =~ ^[,]$ ]]; then | |
sed -i "" $prev_line_num's/,//g' ${file} | |
fi | |
fi | |
sed -i "" "${line_num}d" "${file}" | |
echo "removed: 1, line number: ${line_num}, remaining: $((--count))" | |
return 0 | |
} |
Follows: Google Shell Style Guide,