diff --git a/anagram.sh b/anagram.sh index 129478e..74af473 100755 --- a/anagram.sh +++ b/anagram.sh @@ -1,16 +1,22 @@ #!/bin/bash word=$(echo $1 | xargs) +dictionary="${2:-words.txt}" if [[ $word = "" ]]; then - echo "usage: ./anagram.sh " + echo "usage: ./anagram.sh " exit 1 fi +if [ ! -f "sorted$dictionary" ]; then + echo "Sorted dictionary not found. Generating (this will take a while)..." + bash sorter.sh $dictionary + echo "Done!" +fi wordsorted=$(echo $word | grep -o . | sort | tr -d "\n") -lines=$(grep -xin -- "$wordsorted" sortedwords.txt | sed -e 's/:.*//g') +lines=$(grep -xin -- "$wordsorted" sorted$dictionary | sed -e 's/:.*//g') if [[ $lines = "" ]]; then echo "No matches." exit 0 fi readarray -t lines <<<"$lines" for i in "${lines[@]}"; do - sed "${i}q;d" words.txt | tr '[:upper:]' '[:lower:]' + sed "${i}q;d" $dictionary | tr '[:upper:]' '[:lower:]' done diff --git a/sorter.sh b/sorter.sh new file mode 100755 index 0000000..06efc56 --- /dev/null +++ b/sorter.sh @@ -0,0 +1,6 @@ +#!/bin/bash +inputfile=$1 +rm "sorted$inputfile" &>/dev/null +while IFS= read -r line; do + echo $(printf "%s\n" "$line" | sed -- 's/./\0\n/g' | sort | tr -d -- "\n") >> sorted$inputfile +done < $inputfile