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 compatible) matching the pattern?
到一个冒号分隔的文件名字符串(即PATH兼容)匹配模式?
i.e. echo /var/lib/gems/*/bin
will return
即echo / var / lib / gems / * / bin将返回
/var/lib/gems/1.8/bin /var/lib/gems/1.9.1/bin
I want
我想要
/var/lib/gems/1.8/bin:/var/lib/gems/1.9.1/bin
instead.
代替。
The obvious approach is simply to replace the space character with ':' via tr
, but that doesn't work if the filename itself contains the space character.
显而易见的方法是简单地用':'通过tr替换空格字符,但如果文件名本身包含空格字符则不起作用。
6 个解决方案
#1
17
Actually, I thought of a better solution: use a shell function.
实际上,我想到了一个更好的解决方案:使用shell函数。
function join() {
local IFS=$1
shift
echo "$*"
}
mystring=$(join ':' /var/lib/gems/*/bin)
#2
9
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
#3
4
PATH="$(printf "%s:" /usr/*/bin)"
PATH="${PATH%:}"
#4
2
printf "%s\n" /var/lib/gems/*/bin | tr "\n" ":"
#5
2
It's pretty trivial if you drop into Perl:
如果你进入Perl,这是非常微不足道的:
perl -e 'print join ":", @ARGV' /var/lib/gems/*/bin
Or Python:
或者Python:
python -c 'import sys; print ":".join(sys.argv[1:])' /var/lib/gems/*/bin
Or any number of other popular scripting languages.
或者任何其他流行的脚本语言。
#6
0
Another oneliner: printf "%s\n" /var/lib/gems/*/bin | paste -s -d':'
另一个oneliner:printf“%s \ n”/ var / lib / gems / * / bin |粘贴-s -d':'
But @timo's answer is better in my opinion.
但在我看来,@ timo的回答更好。
#1
17
Actually, I thought of a better solution: use a shell function.
实际上,我想到了一个更好的解决方案:使用shell函数。
function join() {
local IFS=$1
shift
echo "$*"
}
mystring=$(join ':' /var/lib/gems/*/bin)
#2
9
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
#3
4
PATH="$(printf "%s:" /usr/*/bin)"
PATH="${PATH%:}"
#4
2
printf "%s\n" /var/lib/gems/*/bin | tr "\n" ":"
#5
2
It's pretty trivial if you drop into Perl:
如果你进入Perl,这是非常微不足道的:
perl -e 'print join ":", @ARGV' /var/lib/gems/*/bin
Or Python:
或者Python:
python -c 'import sys; print ":".join(sys.argv[1:])' /var/lib/gems/*/bin
Or any number of other popular scripting languages.
或者任何其他流行的脚本语言。
#6
0
Another oneliner: printf "%s\n" /var/lib/gems/*/bin | paste -s -d':'
另一个oneliner:printf“%s \ n”/ var / lib / gems / * / bin |粘贴-s -d':'
But @timo's answer is better in my opinion.
但在我看来,@ timo的回答更好。