Advertisement
bash-masters

lib.file.read.each line

Feb 7th, 2013
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.88 KB | None | 0 0
  1. Automatically generated I/O parser. Methods can be custom defined by delimiter or length. char, chunk and line are popular methods. Demonstration of line method follows.
  2.  
  3. The parser tries to keep track of bytes read, and records read, attempting to read source from a list of file parameters or stdin. If an output file is not specified, a temporary file is created, and the data is sourced from that file, otherwise, an -o option specifies a new script resource exhibiting its own behavior. lib.file.read.each bootstraps itself by performing a regular expression match and replace on auto-exported source environment variables. The %ish variable names are special to the function shortcuts for the declared environment.
  4.  
  5. $ echo hello | lib.file.read.each line '(( %- )) && echo $LINE || echo -n $LINE;'
  6. hello
  7. $ lib.file.read.each line '(( %- )) && echo -E $%_ || echo -En $%_;' -o /dev/stdout;
  8. #!/bin/bash
  9.  
  10. declare -- RS=$'\n';
  11. declare -- RL="1";
  12. declare -- LINE="";
  13. declare -- FILE="";
  14. declare -i FPOS="0";
  15. declare -i EOF="0";
  16. declare -i RC="0";
  17.  
  18. builtin trap 'for trap in "${TRAP[@]}"; do eval $trap; done; unset trap' RETURN;
  19.  
  20. new.shared.return.trap()
  21. {
  22.     TRAP[${#TRAP[@]}]="${*}";
  23. }
  24.  
  25. _auto_return_trap() {
  26.     unset -f /dev/stdout new.shared.return.trap _auto_return_trap;
  27.     unset -v TRAP;
  28. }
  29.  
  30. # custom init section for autotrap ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  31. # new.shared.return.trap 'echo user trap'
  32.  
  33.  
  34. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  35.  
  36. new.shared.return.trap _auto_return_trap;
  37.  
  38. /dev/stdout ()
  39. {
  40. (( EOF )) && echo -E $LINE || echo -En $LINE;
  41.  
  42. }
  43.  
  44. for FILE in "${@:-/dev/stdin}"; do
  45.     EOF == 0;
  46.     while (( ! EOF )); do
  47.         IFS='' builtin read -rd"$RS" LINE || EOF=1;
  48.         let FPOS+=${#LINE} RC++;
  49.         [[ "$LINE" == $'\0' ]] && let FPOS++;
  50.         /dev/stdout || { return $? 2>/dev/null || exit $?; }
  51.     done < "$FILE";
  52. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement