Skip to content

Instantly share code, notes, and snippets.

@agam
Last active February 4, 2020 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agam/e84a7a287a63315abfdd2de125fec022 to your computer and use it in GitHub Desktop.
Save agam/e84a7a287a63315abfdd2de125fec022 to your computer and use it in GitHub Desktop.
Shell script with separate function to read and write out while appending to given multi-line section
#INPUT_FILE=/Users/abrahma/tmp/missing.properties
#OUTPUT_FILE=/Users/abrahma/tmp/output1.properties
#EXISTING_FILE=/Users/abrahma/tmp/existing.properties
EXISTING_FILE=/Users/abrahma/tmp/spaces.properties
OUTPUT_FILE=/Users/abrahma/tmp/output.properties
KEY="^\s*rest.extension.classes"
NEWVAL="io.confluent.connect.replicator.monitoring.ReplicatorMonitoringExtension"
replace_rest_extensions() {
#echo "Replacing ..."
# Modes
# 0 -> looking for match
# 1 -> within match
# 2 -> done with match
mode=0
while IFS= read -r line; do
#echo "Debug: read *$line*, mode is *$mode*"
if [ $mode -eq 0 ]; then
# Check for match
if ! [[ -z $(grep $KEY <<< $line) ]]
then
mode=1
else
# Passthrough line
echo "$line"
fi
fi
# If we were looking at single- or multi-line match earlier, or just got triggered ...
if [ $mode -eq 1 ]; then
# If we ever encounter our value, then we don't need to do anything here.
has_value_already=$(grep $NEWVAL <<< $line)
if ! [[ -z $has_value_already ]]; then
echo "$line"
mode=2
else
# If line terminates with backslash, passthrough
# Otherwise, add on our value to the end (and we're done with this section)
has_backslash=$(grep '\\$' <<< $line)
if ! [[ -z $has_backslash ]]
then
#echo "Debug: backslash, continue..."
echo "$line"
else
#echo "Debug: No backslash, done with match..."
echo "$line,$NEWVAL"
mode=2
fi
fi
else
# Done with matching section: Passthrough output, until end of file
echo $line
fi
done < $EXISTING_FILE > $OUTPUT_FILE
}
# Get existing line
existing_line=$(grep "$KEY" $EXISTING_FILE)
echo "Existing: [$existing_line]"
if [[ -z $existing_line ]]; then
echo "Nothing found!"
modifiedline="$KEY=$NEWVAL"
cat < $INPUT_FILE > $OUTPUT_FILE
echo $modifiedline >> $OUTPUT_FILE
else
replace_rest_extensions
fi
@agam
Copy link
Author

agam commented Feb 4, 2020

Updated to skip existing multi-line entries with the desired value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment