Last active
February 4, 2020 05:40
-
-
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
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
#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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to skip existing multi-line entries with the desired value.