regex and pattern matching with awk

Filter rows that start with ‘r’ or ‘b’

awk '/^[rb]/' /etc/passwd

Filter rows that contain ‘G’ in the third column

df -h | awk '$3 ~ /G/'

Sum rows that contain ‘G’ in the third column

df -h | awk '$3 ~ /G/ { n+=$3 } END { print n }'

Filter rows containing ‘G’ in the third column and the first column start with ‘/dev/sd’ followed by the range of ‘a-z’

df -h | awk '$3 ~ /G/ { if( $1 ~ "/dev/sd[a-z]") print }'

Filter rows that have ‘a’ value in the first column and that contain ‘1’ in the second column

echo -e "a 1x\nb 2y" | awk '{ if ( $1 == "a" && $2 ~ /1/ ) print }'

Filter rows that have ‘httpd’ value in the second column and that contain value greater than 0 in columns 3 and 4

ps -A --sort -rss -o pid,comm,pcpu,pmem | awk '$2 ~ /httpd/ && ( ($3>0) || ($4>0) )'
Advertisements

cut time in kernel or apache log

cut last time error in kernel log

awk '/erro/ {print $1,$2,$3}' /var/log/messages | tail -1

cut last time error in apache log

awk '/erro/ {print $1,$2,$3,$4,$5}' /var/log/httpd/error_log | tail -1 | tr -d []
#!/bin/bash
# cut last time error in both kernel and apache log

for i in /var/log/messages /var/log/httpd/error_log; do
  grep 'erro' $i | tail -1 | egrep -o '.*([0-9]){2}:[0-9]{2}|.*([0-9]){2}:[0-9]{2} [0-9]{4}' | tr -d [
done

Filtrar IP de Host Linux

Filtrar todos IPs do Host comando ip

ip addr | awk '/inet /{print $2}'

Filtrar segundo IP do comando ip

ip addr | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sed -n 2p

Pegar IP de gateway com comando ip

ip route | awk '/default/{print $3}'

Filtrar terceiro IP do comando ifconfig

ifconfig | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | sed -n 3p

Pegar IP de gateway com comando route

route -n | awk '/^0.0.0.0/ {print $2}'