Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Youni Bash tutorial
- # Parse File And Sort Strings: Key="number"
- # cat db
- # a="1110"
- # b="100"
- # C="1000"
- #
- # Expected result:
- # b="100"
- # C="1000"
- # a="1110"
- file='db'
- #parse database file and fill arrays of keys and values
- i=0
- while IFS= read -r line
- do
- i=$((i+1))
- echo "Pasrse line: $line";
- #key=$(echo $line | cut -d= -f1 | sed 's/[^_0-9A-Za-z]*\([_0-9A-Za-z]*\)[^_0-9A-Za-z]*/\1/')
- key=$(echo $line | cut -d= -f1 | grep -Po -m1 '[_A-Za-z]*')
- value=$(echo $line | cut -d= -f2 | grep -Po '[0-9]*' | head -n1)
- #value=$(echo $line | cut -d= -f2 | awk -F'[^0-9]*' '$0=$2')
- if [ -z $key ] || [ -z $value ]
- then
- echo Line $i is not valid
- exit 1
- fi
- echo " key: $key"
- echo " value: $value"
- arr_keys[$i]=$key
- arr_values[$i]=$value
- done < $file
- qnty=$i
- #sort array by values numbers ascending
- i=0
- while [ $i -lt $qnty ]
- do
- i=$((i+1))
- j=$i
- while [ $j -lt $qnty ]
- do
- j=$((j+1))
- if [[ ${arr_values[$j]} -lt ${arr_values[$i]} ]]
- then
- #swap
- key=${arr_keys[$i]}
- value=${arr_values[$i]}
- arr_keys[$i]=${arr_keys[$j]}
- arr_values[$i]=${arr_values[$j]}
- arr_keys[$j]=$key
- arr_values[$j]=$value
- fi
- done
- done
- #print result array
- echo
- echo 'Result array:'
- i=0
- while [ $i -lt $qnty ]
- do
- i=$((i+1))
- echo ${arr_keys[$i]}'="'${arr_values[$i]}'"'
- #put the result to file
- # touch __tmp__
- # echo ${arr_keys[$i]}'="'${arr_values[$i]}'"' >> __tmp__
- done
- # mv __tmp__ $file
Advertisement
Add Comment
Please, Sign In to add comment