Difference between revisions of "Replace set of lines in a file with output lines of other command using shell script"
From Notes_Wiki
(Created page with "<yambe:breadcrumb>Useful_bash_shell_scripts|Useful bash shell scripts</yambe:breadcrumb> =Replace set of lines in a file with output lines of other command using shell script=...") |
m |
||
Line 1: | Line 1: | ||
[[Main_Page|Home]] > [[Shell scripting]] > [[Useful bash shell scripts]] > [[Replace set of lines in a file with output lines of other command using shell script]] | |||
Use: | Use: | ||
Line 51: | Line 50: | ||
[[Main_Page|Home]] > [[Shell scripting]] > [[Useful bash shell scripts]] > [[Replace set of lines in a file with output lines of other command using shell script]] |
Latest revision as of 13:38, 7 April 2022
Home > Shell scripting > Useful bash shell scripts > 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