Browse Source

make file truncation a function

George Jones 3 năm trước cách đây
mục cha
commit
11c5ddf0e2
1 tập tin đã thay đổi với 31 bổ sung10 xóa
  1. 31 10
      some

+ 31 - 10
some

@@ -6,11 +6,27 @@
 # Helper functions
 PROG=`basename "$0" | tr -d '\n'`
 
-function info()  { echo ${PROG}\: info: "$@" 1>&2; }
-function warn()  { echo ${PROG}\: warning: "$@" 1>&2; }
-function error() { echo ${PROG}\: error: "$@" 1>&2; }
-function debug() { [[ -v DEBUG ]] && echo ${PROG}\: debug: "$@" 1>&2 || true ; }
-function die()   { echo ${PROG}\: fatal: "$@" 1>&2 && exit 1; }
+function info()  { echo `date +%c` ${PROG}\: info: "$@" 1>&2; }
+function warn()  { echo `date +%c` ${PROG}\: warning: "$@" 1>&2; }
+function error() { echo `date +%c` ${PROG}\: error: "$@" 1>&2; }
+function debug() { [[ -v DEBUG ]] && echo `date +%c` ${PROG}\: debug: "$@" 1>&2 || true ; }
+function die()   { echo `date +%c` ${PROG}\: fatal: "$@" 1>&2 && exit 1; }
+
+function truncate() {
+    # trunchate a FILE to MAXLINES
+
+    local FILE=$1
+    local MAXLINES=$2
+
+    local TEMP=`mktemp`
+
+    cp ${FILE} ${TEMP} && \
+        tail -${MAXLINES} ${TEMP} > \
+             ${FILE} && \
+        rm ${TEMP}
+}
+
+
 
 function someFunc {
     # Functon to print "some" lines of a file, like head or tail but, random start
@@ -46,9 +62,15 @@ function someFunc {
 
         FILE="$2"
     fi
+    # TODO add real getopt parsing
+    # TODO add -m|middle option to select lines from the middle
 
     # Count the lines to bound display
     LINES=`wc -l $FILE | sed -e 's/ .*//'`
+    # TODO Do something sensible for stdin here
+    #      Either
+    #         - Save /dev/stdin to a tmp file (up to a max?), count THAT and use as FILE
+    #         - revert to head-like behavior (with a timeout?)  (since we have no idea how long stdin is)
 
     # pick a random starting line at least HOW_MANY back from the end
     FIRST=$((1 + RANDOM % (LINES - HOW_MANY + 1 )))
@@ -57,12 +79,11 @@ function someFunc {
     LAST=$((FIRST + HOW_MANY - 1))
     LAST=$((LAST>LINES ? LINES : LAST))
 
-    # display line numbers to stderr to allow re-extraction of randomly chosen lines
-    echo some: lines $FIRST to $LAST \(of $LINES\) of $FILE |& tee /dev/stderr >> ${SOMELOG}
-    # only keep MAXLOG lines of SOMELOG
-    mv ${SOMELOG} ${SOMELOG}.$$ && tail -${MAXLOG} ${SOMELOG}.$$ > ${SOMELOG} && rm ${SOMELOG}.$$
-
+    # log line numbers to allow re-extraction of randomly chosen lines
+    info lines $FIRST to $LAST \(of $LINES\) of `readlink -f $FILE` |& tee /dev/stderr >> ${SOMELOG}
 
+    # only keep MAXLOG lines of SOMELOG
+    truncate $SOMELOG $MAXLOG
 
     # Let's see some lines !
     awk "NR >= $FIRST && NR <= $LAST" $FILE