-1

I have a list called Artists.dat. I want to sort the artists based on how old they were when they died. Then print the following for each.

"first name" "last name" lived for "$4-$3" years.

e.g. Dorotha Tanning lived for 102 years. (sorted by $4-$3)

Dorothea,  Tanning, 1910, 2012
Frida,     Kahlo, 1907, 1954
Gertrude,  Abercrombie, 1909, 1977
Leonora,   Carrington, 1917, 2011
Max,       Ernst, 1891, 1976
Remedios,  Varo, 1908, 1963
Rene,      Magritte, 1898, 1967
Salvador,  Dali, 1904, 1989
Yves,      Tanguy, 1900, 1955
2

If you have a recent version of GNU awk

gawk -F', *' '
  {a[$1" "$2]=$4-$3}
  END {
    PROCINFO["sorted_in"]="@val_num_desc"
    for (i in a) print i, "lived for", a[i], "years"
  }
' Artists.dat
1

While steeldriver's solution is much more elegant, I offer this one as well..

awk -F"," '{print $1, $2, "lived for "$4-$3" years."}' Artists.dat|tr -s " "| sort -nrk5
0

Here's an effort in python as well --

/artists.py
Dorothea Tanning lived for 102 years
Leonora Carrington lived for 94 years
Salvador Dali lived for 85 years
Max Ernst lived for 85 years
Rene Magritte lived for 69 years
Gertrude Abercrombie lived for 68 years
Remedios Varo lived for 55 years
Yves Tanguy lived for 55 years
Frida Kahlo lived for 47 years


cat artists.py 
#!/usr/bin/python
d = {}
for line in open("artists.dat", "r"):
  parts = line.strip().split(",")
  name = parts[0].strip() + " " + parts[1].strip()
  age_died = int(parts[3]) - int(parts[2])    
  d[name] = age_died

for i in sorted(d, key=d.get, reverse=True):
  print("%s lived for %d years" %(i, d[i]))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.