Issue
I'm trying to pass a single variable into my sed's search/replace to eliminate duplicate code and make further edits to string easier. Here is my original code:
function dhcplog() {
cat /var/log/pihole.log | grep --line-buffered dhcp | sed -E '/DHCP, |DHCPACK|DHCPNAK|not giving/a \\'
tail -f /var/log/pihole.log | grep --line-buffered dhcp | sed -E '/DHCP, |DHCPACK|DHCPNAK|not giving/a \\'
}
and here is the code I'm trying to achieve, by passing the string into both seds with single variable:
function dhcplog() {
SEQUENCE="/DHCP, |DHCPACK|DHCPNAK|RTR-SOLICIT|not giving|router advertisement on/a \\"
FILE="/var/log/pihole.log"
cat $FILE | grep --line-buffered dhcp | sed -E "$SEQUENCE"
tail -f $FILE | grep --line-buffered dhcp | sed -E "$SEQUENCE"
}
but I always end up with -bash: SEQUENCE: command not found followed by unmodified output (it should place newlines after lines with matches).
edit: after @KamilCuk's fix the output works, but sed refuses to parse it (it should place newlines after lines with matches):
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPACK(eth0) 192.168.2.168 b0:55:08:05:bb:1a DEVICE
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPREQUEST(eth0) 192.168.2.168 b0:55:08:05:bb:1a
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPACK(eth0) 192.168.2.168 b0:55:08:05:bb:1a DEVICE
Aug 11 15:38:34 dnsmasq-dhcp[444]: RTR-SOLICIT(eth0) b0:55:08:05:bb:1a
Desired output (reproduced with old function):
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPACK(eth0) 192.168.2.168 b0:55:08:05:bb:1a DEVICE
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPREQUEST(eth0) 192.168.2.168 b0:55:08:05:bb:1a
Aug 11 15:38:33 dnsmasq-dhcp[444]: DHCPACK(eth0) 192.168.2.168 b0:55:08:05:bb:1a DEVICE
Aug 11 15:38:34 dnsmasq-dhcp[444]: RTR-SOLICIT(eth0) b0:55:08:05:bb:1a
Solution
After learning a bit about parameter unpacking and thanks to Use sed to replace regex with a variable, I was able to achieve my goal with:
function dhcplog() {
SEQUENCE='/DHCP, |DHCPACK|DHCPNAK|RTR-SOLICIT|not giving|router advertisement on|no address range available for DHCPv6 request via/a \\'
FILE="/var/log/pihole.log"
cat $FILE | grep --line-buffered dhcp | sed -E "${SEQUENCE}"
tail -f $FILE | grep --line-buffered dhcp | sed -E "${SEQUENCE}"
}
@William Pusell's solution is also valid, and appears tad more elegant.
function dhcplog() {
SEQUENCE='/DHCP, |DHCPACK|DHCPNAK|RTR-SOLICIT|not giving|router advertisement on|no address range available for DHCPv6 request via/a \\'
FILE="/var/log/pihole.log"
cat $FILE | grep --line-buffered dhcp | sed -E "$SEQUENCE"
tail -f $FILE | grep --line-buffered dhcp | sed -E "$SEQUENCE"
}
Thank you, and feel free to direct me to a source explaining differences between "$SEQUENCE" and "${SEQUENCE}" ^_^
Answered By - jackar Answer Checked By - Timothy Miller (WPSolving Admin)