From Notes Wiki
Jump to: navigation, search
Home > Shell scripting > Useful bash shell scripts > Replace set of lines in a file with output lines of other command using shell script

Replace set of lines in a file with output lines of other command using shell script

Use:

REPLACE_START_LINE=6
REPLACE_MAX_LINE_COUNT=5
COMMAND=ls
REPLACE_FILE=test-config.txt

LINE_LIST=$($COMMAND | tee output.txt)
LINE_COUNT=$(wc -l output.txt | grep -o [0-9]*)

rm -f output.txt

for LINE1 in $LINE_LIST; do
	sed -i "$REPLACE_START_LINE c$LINE1" $REPLACE_FILE
	REPLACE_START_LINE=$(( $REPLACE_START_LINE + 1 ))
done

LINES_LEFT=$(( REPLACE_MAX_LINE_COUNT - LINE_COUNT ))
for ((i=0; i<LINES_LEFT; i++)); do
	sed -i "$REPLACE_START_LINE c#Extra line" $REPLACE_FILE
	REPLACE_START_LINE=$(( $REPLACE_START_LINE + 1 ))
done

For example to replace a bunch of lines in iptables based on nslookup use:

REPLACE_START_LINE=6
REPLACE_MAX_LINE_COUNT=5

nslookup api.domain.com | grep Address > nslookup-temp.txt
ADDRESS_COUNT=$(wc -l nslookup-temp.txt | grep -o [0-9]*)
IP_COUNT=$(( $ADDRESS_COUNT - 1 ))
IP_LIST=$(tail -2 nslookup-temp.txt | sed 's/Address: //g')

for IP1 in $IP_LIST; do
	sed -i "$REPLACE_START_LINE ciptables -d $IP1 -j ACCEPT" /etc/sysconfig/iptables
	REPLACE_START_LINE=$(( $REPLACE_START_LINE + 1 ))
done

LINES_LEFT=$(( REPLACE_MAX_LINE_COUNT - IP_COUNT ))
for ((i=0; i<LINES_LEFT; i++)); do
	sed -i "$REPLACE_START_LINE c#Extra line" /etc/sysconfig/iptables
	REPLACE_START_LINE=$(( $REPLACE_START_LINE + 1 ))
done

rm -f nslookup-temp.txt


Home > Shell scripting > Useful bash shell scripts > Replace set of lines in a file with output lines of other command using shell script