youni

Bash Parse File And Sort Strings: Key="number"

Aug 9th, 2021 (edited)
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.46 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Youni Bash tutorial
  4. # Parse File And Sort Strings: Key="number"
  5. # cat db
  6. # a="1110"
  7. # b="100"
  8. # C="1000"
  9. #
  10. # Expected result:
  11. # b="100"
  12. # C="1000"
  13. # a="1110"
  14.  
  15.  
  16. file='db'
  17.  
  18. #parse database file and fill arrays of keys and values
  19. i=0
  20. while IFS= read -r line
  21. do
  22.     i=$((i+1))
  23.     echo "Pasrse line: $line";
  24.     #key=$(echo $line | cut -d= -f1 | sed 's/[^_0-9A-Za-z]*\([_0-9A-Za-z]*\)[^_0-9A-Za-z]*/\1/')
  25.     key=$(echo $line | cut -d= -f1 | grep -Po -m1 '[_A-Za-z]*')
  26.     value=$(echo $line | cut -d= -f2 | grep -Po '[0-9]*' | head -n1)
  27.     #value=$(echo $line | cut -d= -f2 | awk -F'[^0-9]*' '$0=$2')
  28.     if [ -z $key ] || [ -z $value ]
  29.     then
  30.         echo Line $i is not valid
  31.         exit 1
  32.     fi
  33.     echo "  key: $key"
  34.     echo "  value: $value"
  35.     arr_keys[$i]=$key
  36.     arr_values[$i]=$value
  37. done < $file
  38.  
  39. qnty=$i
  40.  
  41. #sort array by values numbers ascending
  42. i=0
  43. while [ $i -lt $qnty ]
  44. do
  45.     i=$((i+1))
  46.     j=$i
  47.     while [ $j -lt $qnty ]
  48.     do
  49.         j=$((j+1))
  50.         if [[ ${arr_values[$j]} -lt ${arr_values[$i]} ]]
  51.         then
  52.             #swap
  53.             key=${arr_keys[$i]}
  54.             value=${arr_values[$i]}
  55.             arr_keys[$i]=${arr_keys[$j]}
  56.             arr_values[$i]=${arr_values[$j]}
  57.             arr_keys[$j]=$key
  58.             arr_values[$j]=$value
  59.         fi
  60.     done
  61. done
  62.  
  63. #print result array
  64. echo
  65. echo 'Result array:'
  66. i=0
  67. while [ $i -lt $qnty ]
  68. do
  69.     i=$((i+1))
  70.     echo ${arr_keys[$i]}'="'${arr_values[$i]}'"'
  71.     #put the result to file
  72.     # touch __tmp__
  73.     # echo ${arr_keys[$i]}'="'${arr_values[$i]}'"' >> __tmp__
  74. done
  75. # mv __tmp__ $file
  76.  
Advertisement
Add Comment
Please, Sign In to add comment