Globbing/pathname expansion with colon as separator

前端 未结 8 1296
鱼传尺愫
鱼传尺愫 2020-12-28 16:23

How can I convert a string containing glob characters such as

/var/lib/gems/*/bin

into a colon-separated string of filenames (i.e. PATH com

相关标签:
8条回答
  • 2020-12-28 16:36

    without saving IFS and command substitution

    dirs=(/var/lib/gems/*/bin) ; IFS=: eval 'dirs="${dirs[*]}"'
    
    0 讨论(0)
  • 2020-12-28 16:39

    Actually, I thought of a better solution: use a shell function.

    function join() {
        local IFS=$1
        shift
        echo "$*"
    }
    
    mystring=$(join ':' /var/lib/gems/*/bin)
    
    0 讨论(0)
  • 2020-12-28 16:41
    PATH="$(printf "%s:" /usr/*/bin)"
    PATH="${PATH%:}"
    
    0 讨论(0)
  • 2020-12-28 16:46

    This should do it for you:

    dirs=(/var/lib/gems/*/bin)    # put filenames (dirnames) in an array
    saveIFS=$IFS IFS=':'          # set the Internal Field Separator to the desired delimiter
    dirs=("${dirs[*]}")           # convert the array to a scalar with the new delimiter
    IFS=$saveIFS                  # restore IFS
    
    0 讨论(0)
  • 2020-12-28 16:46

    Another oneliner: printf "%s\n" /var/lib/gems/*/bin | paste -s -d':'

    But @timo's answer is better in my opinion.

    0 讨论(0)
  • 2020-12-28 16:47

    No need to mess with IFS, zsh can join arrays with a simple variable flag:

    dirs=(/var/lib/gems/*/bin(N))
    dirs=${(j.:.)dirs}
    

    The (N) on the first line suppresses a warning if there are no files; the (j.:.) joins the array with :s. Works with 0, 1, or multiple matches.

    0 讨论(0)
提交回复
热议问题