Skip to content

Instantly share code, notes, and snippets.

@krzysztofantczak
Last active February 20, 2017 10:48
Show Gist options
  • Save krzysztofantczak/ab3233ec700c27f2f59222653656cde6 to your computer and use it in GitHub Desktop.
Save krzysztofantczak/ab3233ec700c27f2f59222653656cde6 to your computer and use it in GitHub Desktop.

file before:

some
stuff
at the top
              <------------------------ place of pasting text with line_before
table ....    <-------------------+
table ....                        |
table ....                        |
                                  |
nat...                            |
nat...                            +----- section matched by multiline regexp
                                  |
block ...                         |
block ...                         |
                                  |
pass...                           |
pass...       <-------------------+
              <------------------------ place of pasting text with line_after
some stuff below
the file

file after:

some
stuff
at the top

# This is some
# multiline text
# injected into file
# with insert_before
table ....
table ....
table ....

nat...
nat...

block ...
block ...

pass...
pass...
# This is some
# multiline text
# injected into file
# with insert_after

some stuff below
the file
#!/bin/sh
# INSERT LINES AFTER A PATTERN
insert_after () {
filename=$1
pattern=$2
text=$3
size=$(cat $filename | wc -l)
patched=$(pcregrep -Mine "${pattern}${text}" $filename | wc -l)
if [ $patched -gt 0 ]; then echo "already patched, skipping..."; return; fi
match=$(pcregrep -Mine "$pattern" $filename)
msize=$(pcregrep -Mine "$pattern" $filename | wc -l)
start=$(echo $match | cut -d: -f1)
end=$(( $start + $msize ))
sed "${end}i\\
${text}" $filename > /tmp/ppf.tmp
mv /tmp/ppf.tmp $filename
}
# INSERT LINES BEFORE PATTERN
insert_before () {
filename=$1
patterns=$2
text="$3"
size=$(cat $filename | wc -l)
patched=$(pcregrep -Mine "${text}${pattern}" $filename | wc -l)
if [ $patched -gt 0 ]; then echo "already patched, skipping..."; return; fi
match=$(pcregrep -Mine "$pattern" $filename)
msize=$(pcregrep -Mine "$pattern" $filename | wc -l)
start=$(echo $match | cut -d: -f1)
sed "${start}i\\
${text}" $filename > /tmp/ppf.tmp
mv /tmp/ppf.tmp $filename
}
reset_pf () {
cp /etc/pf.conf.backup /etc/pf.conf
return
}
#reset_pf
#clear;
pf=/etc/pf.conf
insert_after $pf "(table(\n|.)*pass.*\n)" "#test\\
ext_if=\"hn0\"\\
"
insert_after $pf "nat" "# /NAT\n"
insert_before $pf "table" "#REDIRECTS\\
#sdfs\\
#aqq\\
"
insert_before $pf "^" "# hey"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment