Code:
if [ "$1" = 1 ]
then
{
sorter=""
}
elif [ "$1" = 2 ]
then
{
sorter="-k2 -t :"
}
fi
cars=$(cat Cars.txt | sort $sorter)
echo "$cars" > Cars.txt
while read inputline
do
col1="$(echo $inputline | cut -d: -f1)"
col2="$(echo $inputline | cut -d: -f2)"
col3="$(echo $inputline | cut -d: -f2)"
col4="$(echo $inputline | cut -d: -f2)"
col5="$(echo $inputline | cut -d: -f2)"
printf "%-45s %-20s %-10s %-5s %-8s %-10s\n" "$col1" "$col2" "$col3" "$col4" "$col5" "$total_sales"
done < Cars2.txt # display in sorted format!
##done < Cars.txt | sort $sorter ###THIS WAS ORIGINAL COMMAND THAT DO NOT WORK!
Output:
Car 1 Mitsubihi 13 22 50
Hence, $col1 to 5 will hold the value of the respective field in each row, looping till the whole file is complete.
Code:
Data of Cars.txt (quite a few rows, delimited by colons):
format: Car model:Manufacturer:price:no. sold:no. left
Car 1:Mistubishi:13:22:50
Car 5:Toyota:23:3:2
Catkin,
My apologies for ignoring your earlier post about leaving the sort command out of the string. I did not really notice the difference at first and hence did not carry out your suggestion.
Basically, what this do was to grab the data off Cars.txt and display out all rows in a format. What I wanted to do was to add a "sorting function" so you can sort by Car name, brand, price, etc. So far, I have only added 2 of these.
My original intention was to dynamically assign $sorter value. Hence, the user will select what to sort with, and $sorter will hold the relevant sort command's arguments for that particular selection. However, apparently there is some form of logic error in this as this does not work in the loop. I have verified that this method does work provided if I simply used:
Code:
cat BookDB.txt | sort $sorter
Hence, the interim solution I employed is to sort the file first, store it inside another file (the read line do while loop refuse to let me throw in a variable, only wants a file) and let the sorted file display out the contents. Not very elegant, but at least its working somewhat.
However, I would appreciate if any of you experienced users will care to break down and explain why my intial method do not work? (The intial method is in the code with a ###THIS WAS ORIGINAL COMMAND THAT DO NOT WORK! comment.
Thank you.