Created
June 19, 2018 19:47
-
-
Save rcbop/c4006b41c11035bfb82d456820011dd1 to your computer and use it in GitHub Desktop.
handle properties file with bash using awk and sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#/ Define properties and sort them in a file | |
#/ Usage: | |
#/ set_property key value filename | |
#/ Alternative: | |
#/ | |
#/ export PROPERTIES_FILE=myproperties | |
#/ set_property key value | |
#/ -------------------------------------------------------------------------------- | |
#/ Author: Rogério Peixoto (rcbpeixoto@gmail.com) | |
#/ -------------------------------------------------------------------------------- | |
usage() { grep '^#/' "$0" | cut -c4- ; exit 0 ; } | |
expr "$*" : ".*--help" > /dev/null && usage | |
set_property(){ | |
if [ -z "$1" ]; then | |
echo "No parameters provided, exiting..." | |
exit 1 | |
fi | |
if [ -z "$2" ]; then | |
echo "Key provided, but no value, breaking" | |
exit 1 | |
fi | |
if [ -z "$3" ] && [ -z "$PROPERTIES_FILE" ]; then | |
echo "No file provided or PROPERTIES_FILE is not set, exiting..." | |
exit 1 | |
fi | |
if [ "$PROPERTIES_FILE" ] && [ "$3" ]; then | |
echo "PROPERTIES_FILE variable is set AND filename in comamnd! Use only or the other. Exiting..." | |
exit 1 | |
else | |
if [ "$3" ] && [ ! -f "$3" ]; then | |
echo "File in command NOT FOUND!" | |
exit 1 | |
elif [ "$PROPERTIES_FILE" ] && [ ! -f "$PROPERTIES_FILE" ]; then | |
echo "File in PROPERTIES_FILE variable NOT FOUND!" | |
exit 1 | |
fi | |
fi | |
if [ "$PROPERTIES_FILE" ]; then | |
file=$PROPERTIES_FILE | |
else | |
file=$3 | |
fi | |
tempfile=$(mktemp "/tmp/$file.XXXXXX") | |
existing=$(cat $file | grep $1=) | |
if [ -z $existing ]; then | |
cat $file >> $tempfile | |
echo "$1=$2" >> $tempfile | |
else | |
awk -v pat="^$1=" -v value="$1=$2" '{ if ($0 ~ pat) print value; else print $0; }' "$file" > "$tempfile" | |
fi | |
sort_tempfile=$(mktemp "/tmp/$file.XXXXXX") | |
cat $tempfile | sort > "$sort_tempfile" | |
tempfile=$sort_tempfile | |
mv "$tempfile" "$file" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment