Globbing/pathname expansion with colon as separator

白昼怎懂夜的黑 提交于 2019-11-30 06:22:48

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

function join() {
    local IFS=$1
    shift
    echo "$*"
}

mystring=$(join ':' /var/lib/gems/*/bin)

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
PATH="$(printf "%s:" /usr/*/bin)"
PATH="${PATH%:}"
printf "%s\n" /var/lib/gems/*/bin | tr "\n" ":"

It's pretty trivial if you drop into Perl:

perl -e 'print join ":", @ARGV' /var/lib/gems/*/bin

Or Python:

python -c 'import sys; print ":".join(sys.argv[1:])' /var/lib/gems/*/bin

Or any number of other popular scripting languages.

without saving IFS and command substitution

dirs=(/var/lib/gems/*/bin) ; IFS=: eval 'dirs="${dirs[*]}"'

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!