Parse URL in shell script

后端 未结 14 1774
一生所求
一生所求 2020-12-02 20:55

I have url like:

sftp://user@host.net/some/random/path

I want to extract user, host and path from this string. Any part can be random lengt

14条回答
  •  生来不讨喜
    2020-12-02 21:36

    If you really want to do it in shell, you can do something as simple as the following by using awk. This requires knowing how many fields you will actually be passed (e.g. no password sometimes and not others).

    #!/bin/bash
    
    FIELDS=($(echo "sftp://user@host.net/some/random/path" \
      | awk '{split($0, arr, /[\/\@:]*/); for (x in arr) { print arr[x] }}'))
    proto=${FIELDS[1]}
    user=${FIELDS[2]}
    host=${FIELDS[3]}
    path=$(echo ${FIELDS[@]:3} | sed 's/ /\//g')
    

    If you don't have awk and you do have grep, and you can require that each field have at least two characters and be reasonably predictable in format, then you can do:

    #!/bin/bash
    
    FIELDS=($(echo "sftp://user@host.net/some/random/path" \
       | grep -o "[a-z0-9.-][a-z0-9.-]*" | tr '\n' ' '))
    proto=${FIELDS[1]}
    user=${FIELDS[2]}
    host=${FIELDS[3]}
    path=$(echo ${FIELDS[@]:3} | sed 's/ /\//g')
    

提交回复
热议问题