sortsheets 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/bash
  2. # (c) J.Reisenweber 2016, GPLv2
  3. # Usage:
  4. # [verbose=true|quiet=true] sortsheets <rootsheet.sch>
  5. #
  6. # each(!) sheet except index/rootsheet #1 MUST have a comment4 of exactly
  7. # Xsheetnumber=<int>
  8. # sheet numbers must be unique
  9. set -e
  10. #this is not really safe
  11. : ${quiet:=false} # true: less output
  12. : ${verbose:=false} # true: more output
  13. $verbose && quiet=false
  14. if ! [ -w "$1" ]; then
  15. cat <<'ETX'
  16. (c) J.Reisenweber 2016, GPLv2
  17. Usage:
  18. [verbose=true|quiet=true] sortsheets <rootsheet.sch>
  19. each(!) sheet except index/rootsheet (1) MUST have a comment4 of exactly
  20. Xsheetnumber=<int>
  21. sheet numbers must be unique
  22. ETX
  23. echo "Error: file parameter \"$1\" not writable. Quit"
  24. exit 1
  25. fi
  26. tmp=$(mktemp -dt -p .)
  27. trap "rm -r $tmp" EXIT
  28. # helper file for sed
  29. cat >$tmp/firstsheet.sed <<-ETX
  30. : start
  31. /\\\$Sheet/,/\\\$EndSheet/ {p}
  32. /\\\$EndSheet/ ! {n;b start}
  33. : rest
  34. n
  35. w $tmp/rest.0sch
  36. b rest
  37. ETX
  38. #get header
  39. sed '/\$Sheet/ Q' $1 >$tmp/header.0sch
  40. $verbose && ls -l $tmp/header.0sch
  41. # split out the $Sheet $EndSheet sections into separate files, plus rest
  42. cp $1 $tmp/trest.0sch
  43. for (( n=2; n<=$(grep -c '$EndSheet' $1)+1; n++ )); do
  44. sed -n -f $tmp/firstsheet.sed $tmp/trest.0sch >$tmp/dollarsheet$(( 100 + n )).0sch;
  45. cp $tmp/rest.0sch $tmp/trest.0sch
  46. $verbose && ls -l $tmp/rest.0sch
  47. $verbose && ls -l $tmp/dollarsheet$(( 100 + n )).0sch
  48. $verbose && echo ====================
  49. done
  50. # dereference sheet files and fetch their comment4 to
  51. # create according sorted newdollarsheet files
  52. for f in $tmp/dollarsheet*.0sch; do
  53. filename=$(sed -n '/^F1 "/ {s/F1 \"\([^"]*\)".*/\1/; p}' $f); #"
  54. sheetnumber=$(sed -n '/Comment4/ {s/Comment4 "Xsheetnumber=\([^"]*\)"/\1/; p}' $filename); #"
  55. $quiet || echo "$f - $filename: sheetnumber $sheetnumber"
  56. mv -n $f $tmp/newdollarsheet$(( sheetnumber +100 )).0sch \
  57. || { echo "error! ${filename}: duplicate sheet number $sheetnumber in comment4"; exit 2; };
  58. done
  59. #create new rootsheet
  60. cat $tmp/header.0sch $tmp/newdollarsheet*.0sch $tmp/rest.0sch >$tmp/rootsheet.new
  61. cp $1 $1.ssbak
  62. mv $tmp/rootsheet.new $1
  63. $quiet || echo "created new $1 - backup in $1.ssback"
  64. exit