[ACCEPTED]-concatenate inputs in bash script-unix

Accepted answer
Score: 13
function concatenate_args
{
    string=""
    for a in "$@" # Loop over arguments
    do
        if [[ "${a:0:1}" != "-" ]] # Ignore flags (first character is -)
        then
            if [[ "$string" != "" ]]
            then
                string+="_" # Delimeter
            fi
            string+="$a"
        fi
    done
    echo "$string"
}

# Usage:
args="$(concatenate_args "$@")"

0

Score: 3

This is an ugly but simple solution:

echo $* | sed -e "s/ /_/g;s/[^_]*_//"

0

Score: 3

You can also use formatted strings to concatenate 1 args.

# assuming flag is first arg and optional
flag=$1
[[ $1 = ${1#-} ]] && unset $flag || shift

concat=$(printf '%s_' ${@})
echo ${concat%_} # to remove the trailing _

nJoy!

Score: 2

Here's a piece of code that I'm actually 6 proud of (it is very shell-style I think)

#!/bin/sh

firsttime=yes
for i in "$@" 
do
    test "$firsttime" && set -- && unset firsttime
    test "${i%%-*}" && set -- "$@" "$i"
done

IFS=_ ; echo "$*"

I've 5 interpreted your question so as to remove 4 all arguments beginning with -

If you only want 3 to remove the beginning sequence of arguments 2 beginnnig with -:

#!/bin/sh

while ! test "${1%%-*}"
do
    shift
done

IFS=_ ; echo "$*"

If you simply want to remove 1 the first argument:

#!/bin/sh

shift
IFS=_ ; printf %s\\n "$*"
Score: 1
flag="$1"
shift
oldIFS="$IFS"
IFS="_"
the_rest="$*"
IFS="$oldIFS"

In this context, "$*" is exactly what you're 6 looking for, it seems. It is seldom the 5 correct choice, but here's a case where 4 it really is the correct choice.

Alternatively, simply 3 loop and concatenate:

flag="$1"
shift
the_rest=""
pad=""
for arg in "$@"
do
    the_rest="${the_rest}${pad}${arg}"
    pad="_"
done

The $pad variable ensures 2 that you don't end up with a stray underscore 1 at the start of $the_rest.

Score: 0
#!/bin/bash
paramCat () {
for s in "$@" 
do
    case $s in 
        -*)
            ;;
        *) 
            echo -n _${s}
            ;; 
    esac
done
}

catted="$(paramCat "$@")"
echo ${catted/_/} 

0

More Related questions