#!/bin/bash
-# Desc: Outputs text at randomish position within dir of text files
+# Desc: Output random text selection from a text file within a directory
# Usage: randtxt.sh DIR
-# Version 0.0.4
+# Version 0.0.5
# Depends: Bash 5.1.16, GNU findutils 4.8.0, GNU Coreutils 8.32
+# Example: randtxt.sh ~/Calibre\ Library/
-SAMPLE=10000;
-CONTEXT="5000"; # total bytes +1 before and after point within file to print
+SAMPLE=10000; # ceiling for number of text files to consider
+CONTEXT="5000"; # total bytes +1 of text to display
if [[ $(( CONTEXT/2 + CONTEXT/2 )) -lt $CONTEXT ]]; then ((CONTEXT++)); fi;
if [[ $# -gt 1 ]]; then die "FATAL:Too many arguments"; fi;
if [[ $# -lt 1 ]]; then die "FATAL:Not enough arguments"; fi;
if [[ ! -d "$1" ]]; then die "FATAL:Not a dir:$1"; else return 0; fi;
- #yell "DEBUG:checkInput() finished."; # debug
};
getFileSizeList() {
# Desc: Create list of file sizes and paths
mapfile -d '' -t fileSizeList < <(
find -- "$1" -type f -name "*.txt" -printf '%s\t%p\0' | shuf -z -n"$SAMPLE";
); # Build array by feeding null-delimited lines from `find` to `mapfile`
- #declare -p fileSizeList; # debug
declare -g totalSize=0;
local i size;
for i in "${!fileSizeList[@]}"; do
- #declare -p i; # debug
- #yell "DEBUG:fileSizeList[i]:${fileSizeList[i]}"; # debug
size="${fileSizeList[i]%%$'\t'*}";
- #declare -p size; # debug
totalSize=$((totalSize + size));
- #declare -p i size totalSize; # debug
- #yell "=============="; # debug
done;
if [[ $totalSize -le 0 ]]; then die "FATAL:Total size is zero."; fi;
declare -g randPoint
randPoint="$(shuf -n1 -i0-$((totalSize-1)); )";
- #declare -p fileSizeList totalSize randPoint 1>&2;
- #yell "DEBUG:fileSizeList element count:${#fileSizeList[@]}"; # debug
- #yell "DEBUG:getFileSizeList() finished."; # debug
};
getRandText() {
# Desc: Print text within fileSizeList around randPoint
# Output context
file="$(cut -f2- <<< "${fileSizeList[i]}"; )";
printf "INFO:Sample of:%s\n" "$file";
- #head --bytes=$((selEnd + 1 )) -- "$file" | tail --bytes=+$((selStart + 1));
tail --bytes=+$((selStart+1)) -- "$file" | head --bytes=$((selCount));
printf "\n";
return 0;
fi;
psum=$sum; # store previous sum
done;
- #yell "DEBUG:getRandText() finished."; # debug
};
export -f checkInput getFileSizeList getRandText;