在 bash 中,如何将 N 个参数作为空格分隔的字符串连接在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12283463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In bash, how do I join N parameters together as a space separated string
提问by user983124
I'm trying to write a function that takes nparameters and joins them into a string.
我正在尝试编写一个函数,它接受n 个参数并将它们连接成一个字符串。
In Perl it would be
在 Perl 中它会是
my $string = join(' ', @ARGV);
but in bash I don't know how to do it
但在 bash 中我不知道该怎么做
function()
{
??
}
回答by chepner
Check the bashman page for the entry for '*' under Special Parameters.
检查bash手册页中“特殊参数”下的“*”条目。
join () {
echo "$*"
}
回答by Kevin
For the immediate question, chepner's answer("$*") is easiest, but as an example of how to do it accessing each argument in turn:
对于眼前的问题,chepner 的答案( "$*") 是最简单的,但作为如何依次访问每个参数的示例:
func(){
str=
for i in "$@"; do
str="$str $i"
done
echo ${str# }
}
回答by perreal
This one behaves like Perl join:
这个行为就像 Perl join:
#!/bin/bash
sticker() {
delim= # join delimiter
shift
oldIFS=$IFS # save IFS, the field separator
IFS=$delim
result="$*"
IFS=$oldIFS # restore IFS
echo $result
}
sticker , a b c d efg
The above outputs:
以上输出:
a,b,c,d,efg
回答by bsb
Similar to perreal's answer, but with a subshell:
类似于 perreal 的答案,但有一个子外壳:
function strjoin () (IFS=; shift; echo "$*");
strjoin : 1 '2 3' 4
1:2 3:4
Perl's join can separate with more than one character and is quick enough to use from bash (directly or with an alias or function wrapper)
Perl 的 join 可以用多个字符分隔,并且足够快,可以从 bash 使用(直接使用或使用别名或函数包装器)
perl -E 'say join(shift, @ARGV)' ', ' 1 '2 3' 4
1, 2 3, 4

