Advertisement
rockdrilla

dumb way to parse&reconstruct URL, rev.1

Oct 29th, 2013
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. sed_replace() { echo -n "s#$1#$2#g;";}
  2. sed_squeeze() { sed_replace "$1+" "${2:-$1}";}
  3. sed_push() { echo -n 'h;';}
  4. sed_pop() { echo -n 'g;';}
  5. sed_print() { echo -n 'p;';}
  6. sed_script1=$(
  7.   sed_ere_begin() { echo -n "/$1/{"; sed_push;}
  8.   sed_assign() { sed_replace '' "U[$2]='\\$1'";}
  9.   sed_ere_end() { echo '}';}
  10.   sed_ere_begin '^(([^:]+):(\/{0,2}))?(([^:]+):([^@]+)@)?([^:\/]*)?:?([^/]+)?(.*)$'
  11.     sed_assign 1 scheme; sed_print; sed_pop
  12.     sed_assign 5 user; sed_print; sed_pop
  13.     sed_assign 6 pass; sed_print; sed_pop
  14.     sed_assign 7 domain; sed_print; sed_pop
  15.     sed_assign 8 port; sed_print; sed_pop
  16.     sed_assign 9 path; sed_replace '/./' '/'; sed_squeeze '/'; sed_print
  17.     sed_ere_end
  18.   unset -f sed_ere_begin sed_assign sed_ere_end
  19. )
  20. url_parse() {
  21.   sed -nre "${sed_script1}"
  22. }
  23. url_construct() {
  24.   echo ${U[scheme]:-''}${U[user]}${U[pass]:+':'}${U[pass]}${U[user]:+'@'}${U[domain]}${U[port]:+':'}${U[port]}${U[path]:-'/'}
  25. }
  26.  
  27. declare -A U
  28. u1='https://UsErNaMe:My5tR0nGp4s5@domain.ru:8088//./dump.txt'
  29. u2='file:///home/krd/lulz.txt'
  30.  
  31. echo "${u1}" | url_parse
  32. # output:
  33. #   U[scheme]='https://'
  34. #   U[user]='UsErNaMe'
  35. #   U[pass]='My5tR0nGp4s5'
  36. #   U[domain]='domain.ru'
  37. #   U[port]='8088'
  38. #   U[path]='/dump.txt'
  39. eval $(echo "${u1}" | url_parse)
  40. url_construct
  41. # output:
  42. #   https://UsErNaMe:My5tR0nGp4s5@domain.ru:8088/dump.txt
  43.  
  44. echo "${u2}" | url_parse
  45. # output:
  46. #   U[scheme]='file://'
  47. #   U[user]=''
  48. #   U[pass]=''
  49. #   U[domain]=''
  50. #   U[port]=''
  51. #   U[path]='/home/krd/lulz.txt'
  52. eval $(echo "${u2}" | url_parse)
  53. url_construct
  54. # output:
  55. #   file:///home/krd/lulz.txt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement