Commits

Anonymous committed 22511cb

add headtail, took an awk one liner too far

  • Participants
  • Parent commits bd9a73f

Comments (0)

Files changed (1)

+#!/bin/sh
+#exec awk -vh=$((head)) -vt=$((tail)) 'NR<=h;{l[++i%t]=$0}END{j=t;if(NR<h+t){j=NR-h;i=h%t}while(j-->0)print l[++i%t]}' "$@"
+
+head=10
+tail=10
+
+OPTIND=1
+while getopts "h:t:" opt; do
+    case "$opt" in
+        h) head=$OPTARG ;;
+        t) tail=$OPTARG ;;
+    esac
+done
+shift $((OPTIND-1))
+
+pm() { case "$1" in $2) return 0;; esac; return 1; }
+num() {
+    if                     ! pm "$1"      "*[![:digit:]]*" ; then return 0; fi
+    if pm "$1" "0[xX]*" && ! pm "${1#??}" "*[![:xdigit:]]*"; then return 0; fi
+    if pm "$1" "0*"     && ! pm "${1#?}"  "*[![0-7]]*"     ; then return 0; fi
+    return 1;
+}
+
+if ! num "$head" || ! num "$tail"; then
+    printf "%s: head and tail arguments must be numbers\n" "$0" >&2
+    exit 1
+fi
+
+exec awk -vh=$((head)) -vt=$((tail)) '
+NR<=h
+{
+    lines[++i % t] = $0
+}
+END {
+    j=t
+    if (NR < h + t) {
+        j = NR - h
+        i = h % t
+    }
+    while (j-- > 0)
+        print lines[++i % t]
+}
+' "$@"