LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Need help with bash script /simplified sort command/ (https://www.linuxquestions.org/questions/linux-general-1/need-help-with-bash-script-simplified-sort-command-679161/)

szcs 10-26-2008 11:40 AM

Need help with bash script /simplified sort command/
 
Hello!
I'm quite new to Linux...
I would like to make a bash script that works like the "sort" command, but the script itself does not contain the "sort" command.
It should have two options: sorting numerically and lexiologically /with being able to sort with ignoring upper case letters/.
This is how it looks like now:

Code:

#!/bin/bash

#Simplified sort script
#Assuming inputs az space separated words or numbers
#Switches:
#-f <FileName>:The script gets the input data from the file
#-i: Ignore case.
#-n: Sort in numerical mode
#-i and -n can not be defined at the same time

#uncomment this line of you want to see the steps in detailed format
#set -x

#The usage script
usage="Usage: $0 [-f] <FileName> [-i] [-n]"
#Stores the file`s name, if -f is given
fileName=""
#Set to 1 if -i is given
ignoreCase=0
#Set to 1 if -n is given
numerical=0
#Stores the values given by the user, or read from the file
values[0]=0

#Function to sort the values in lexical mode
function sortByName()
{
echo "sortByName $1 $# $@"
echo "$*"
}

#Function to sort the values in numberical mode
function sortByValue()
{
sortedValues[${#}]=0
indexi=0
min=50000000
lastMin=-50000000

for i in ${@}
do
indexj=0

echo "-------------------------"
for j in ${@}
do
if [ ${indexj} -ge ${indexi} ]
then
echo
echo "j: ${j}"
echo "min: ${min}"
echo "lastmin: ${lastMin}"
echo
if [ ${j} -gt ${lastMin} ]
then
if [ ${j} -lt ${min} ]
then
min=${j}
j=50000000
fi
fi
fi
((indexj++))
done
sortedValues[${indexi}]=${min}
lastMin=${min}
((indexi++))
min=50000000
done

for ((i=0;i<=$#;i++))
do
echo -n "${sortedValues[${i}]}"
done

echo
}

#Reads the given switches
while getopts :f:in opt
do
echo "ehhe $opt"
case $opt in
f)
fileName=$OPTARG
;;
i)
if [ $numerical -eq 1 ]
then
echo "-i and -n cannot be set at the same time"
exit;
fi
ignoreCase=1
;;
n)
if [ $ignoreCase -eq 1 ]
then
echo "-i and -n cannot be set at the same time"
exit;
fi
numerical=1
;;
\?)
echo "$usage"
exit
;;
esac
done

#If fileName is given get the values from it
if [ "$fileName" != "" ]
then
values=`cat $fileName`
else
echo "Enter values:"
read values
fi

if [ $numerical -eq 1 ]
then
sortByValue $values
else
sortByName $values
fi

I have problems with making the two processes that do the two types of sorting. What kind of algorithm should I use, and how would that look like in bash? Any advice or help would be great, even with the script above.
Thank you!


All times are GMT -5. The time now is 07:39 AM.