shell-base/modules/editing/replace/replace.sh

40 lines
1.2 KiB
Bash
Raw Normal View History

#!/bin/bash
function replace {
local PATTERN=$1; shift
local NEW_LINE=$1; shift
local FILE=$1; shift
[ ! "$PATTERN" ] || [ ! $FILE ] && return 1
local BEFORE=$1
local NEW=$(echo "${NEW_LINE}" | sed 's/\//\\\//g')
echo finding: $PATTERN Replace with $NEW before $BEFORE in $FILE
touch "${FILE}" || return 1
echo matching: $PATTERN
match=false
if [ "$NEW_LINE" ]; then
sed -i '/'"${PATTERN}"'/{s/.*/'"${NEW}"'/;h};${x;/./{x;q100};{x;q20}}' "${FILE}"
[[ $? -eq 100 ]] && match=true
echo match $match
if [ $match == false ]; then
echo adding new entry $NEW_LINE
if [ "$BEFORE" ]; then
echo searching for $BEFORE to add line before
# sed -i '/'"${BEFORE}"'/{i/.*/'"${NEW}"'/;h};${x;/./{x;q100};x}' "${FILE}"
sed -i '/'"${BEFORE}"'/!{q20};/'"${BEFORE}"'/i\'"${NEW}" "${FILE}"
echo return $?
exit
# ;/i '"${NEW}"'' "${FILE}"
[[ $? -eq 100 ]] && match=true || match=false
echo before match $match
fi
# if [ $match == false ]; then
# echo appending to file
# echo "${NEW_LINE}" >> "${FILE}"
# fi
else echo line matched/replaced
fi
else
sed '/'"${PATTERN}"'/d' "${FILE}"
echo line removed
fi
}