In bash, how do I join N parameters together as a space separated string

天大地大妈咪最大 提交于 2020-05-08 01:40:01

问题


I'm trying to write a function that takes n parameters and joins them into a string.

In Perl it would be

my $string = join(' ', @ARGV);

but in bash I don't know how to do it

function()
{
    ??
}

回答1:


Check the bash man page for the entry for '*' under Special Parameters.

join () {
    echo "$*"
}



回答2:


For the immediate question, chepner's answer ("$*") is easiest, but as an example of how to do it accessing each argument in turn:

func(){
    str=
    for i in "$@"; do 
        str="$str $i"
    done
    echo ${str# }
}



回答3:


This one behaves like Perl join:

#!/bin/bash

sticker() {
  delim=$1      # 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



回答4:


Similar to perreal's answer, but with a subshell:

function strjoin () (IFS=$1; 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 -E 'say join(shift, @ARGV)'  ', '   1 '2 3' 4
1, 2 3, 4


来源:https://stackoverflow.com/questions/12283463/in-bash-how-do-i-join-n-parameters-together-as-a-space-separated-string

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