Back (Current repo: dotfiles)

my dotfiles to make it easy to transfer my settings
To clone this repository:
git clone https://git.viktor1993.net/dotfiles.git
Log | Download | Files | Refs

wordpractice (2462B)


#!/bin/bash

# A crappy little script for myself to help practice memorizing spanish words. Each text file acts as a kind of pack of flashcards.

function summon_dmenu() {
    DIRECTORY="$HOME/spanish_study/vocabulary/"
    FILE=${DIRECTORY}$(find "$DIRECTORY" -maxdepth 1 -type f -regextype posix-extended -regex ".*\.txt$" | sed -E 's/(.*)+\/([^/]+\.txt$)/\2/' | dmenu -l 20 -i -p 'Open which file? (type "any" for random)')

    if [ $FILE = ${DIRECTORY}"any" ]; then
        FILE=$(pick_random_file)
    fi

    if [ ! -f $FILE ]; then
        echo "Missing file!"
        exit 1
    fi

    echo "To exit, answer with :q to quit when prompted for an answer"
}

function pick_random_file() {

    CHOSEN_FILE=$(ls -d ${DIRECTORY}/* | grep -v ${FILE} | awk -v x=$RANDOM 'BEGIN{srand(x);}{line[NR]=$0;}END{print line[(int(rand()*NR+1))];}')
    echo $CHOSEN_FILE
}

function prepare_file() {
    TEMPFILE=$(mktemp --suffix=.txt)
    cat $FILE > $TEMPFILE #we don't want to modify the original file, even accidentally
}

function cleanup_file() {
    rm $TEMPFILE
}

function prompt_user() {
    FLENGTH=$(awk 'END{print NR}' $TEMPFILE)

    if [[ $FLENGTH -eq 0 ]]; then
        echo "Congratulations, you've answered every question!"
        cleanup_file
        read -p "Another? (y/n) " RETRY
        if [[ "$RETRY" == "y" ]]; then
            main
        fi 
        exit 1
    fi

    # we want to be able to pick a random word to test from the file
    function random_num() {
        awk -v y=$1 -v x=$RANDOM 'BEGIN{srand(x); print int(rand()*y+1)}'
    }

    LINE=$(random_num $FLENGTH)

    CHOSEN_LINE=$(awk -v LINE=$LINE '{if(NR==LINE){print $0}}' $TEMPFILE)

    ANSWER=$(echo $CHOSEN_LINE | awk 'BEGIN{FS=":"}{gsub(/^[ ]+|[ ]+$/, "", $2); print $2}')

    QUESTION=$(echo $CHOSEN_LINE | awk 'BEGIN{FS=":"}{gsub(/^[ ]+|[ ]+$/, "", $1); print "What does \x22"$1"\x22 mean?";}')

    read -p "$QUESTION " INPUT

    if [[ "$INPUT" == ":q" ]]; then
        echo "Bye"
        cleanup_file
        exit 1
    fi

    INPUT_LC=$(echo "$INPUT" | awk '{print tolower($0)}')
    ANSWER_LC=$(echo "$ANSWER" | awk '{print tolower($0)}')

    if [[ "$INPUT_LC" == "$ANSWER_LC" ]]; then
        echo "Correct."
        sed -i "${LINE}d" $TEMPFILE
    else
        echo "Incorrect."
        echo "The answer should have been \"${ANSWER}\""
    fi
}

function main() {
    summon_dmenu
    prepare_file

    while true; do
        prompt_user
    done
}

main