0

I am trying to find the oldest model from each car manufacturer in a list of unsorted cars. I am sorting this list in ascending alphabetical order, by manufacturer, model, and year with the following code:

tail +3 cars.csv > cars
shuf cars | cut -d';' -f1 > cars1

car=`head -1 cars1 | tail -1`

echo "When was the first model of the car $car made?"
read car


#Searches the oldest car model
car1=`grep "^$car" cars | sort -n -t';' -k8 | cut -d';' -f8 | head -1 | tail -1`


if [ "$car" -eq "$car1" ] ;
then
    echo "Congratulations! Your answer is correct!"
else
    echo "If you go through the CSV file you'll see that in this case the correct answer is $car1"
fi

rm cars 2> /dev/null
rm cars1 2> /dev/null

Imagine a case where the list goes like this:

Ford Fairmont (auto) : 78

Ford Fairmont: 80

If the question goes like this: When was the first model of the car Ford Fairmont made, and as I'm using the grep command, it will search all the lines that match with Ford Fairmont. In this case, as Ford Fairmont (auto) is the oldest one and contains the words "Ford Fairmont", the program will print the year of Ford Fairmont (auto)'s first model which is 78. How can I get rid of this problem?

  • 1
    Try `grep "^$car;" cars` in your grep command (assuming the delimiter is `;` in the csv file) – M. Nejat Aydin Dec 06 '21 at 22:31
  • 1
    `-eq` is an arithmetic operator. If you want to compare strings then use `=`. – M. Nejat Aydin Dec 06 '21 at 22:40
  • Thank you very much M. Nejat Aydin! – Ruth Mary Thannikuzhuppil Dec 06 '21 at 22:46
  • 1
    BTW, it's a better practice to `rm -f cars` instead of `rm cars 2>/dev/null`, because `rm -f cars` will still print error messages for cases _other than_ the file not existing. You _want_ those errors, because they let you diagnose problems. – Charles Duffy Dec 06 '21 at 23:14
  • 1
    (also, think about reading your content into variables instead of into temporary files; to just read the first line of a file into a variable, `read -r variable – Charles Duffy Dec 06 '21 at 23:16
  • ...btw, for a general overview of arrays in bash, see [BashFAQ #5](https://mywiki.wooledge.org/BashFAQ/005). – Charles Duffy Dec 06 '21 at 23:18
  • BTW, consider using `awk` instead of `grep`. `awk -F';' -v car="$car" '$1 == car { print $0 }'` prints the whole line of your match, but you could change `$0` to `$2` to print only the number, f/e – Charles Duffy Dec 06 '21 at 23:21

0 Answers0