bash separate parameters with specific delimiter

不想你离开。 提交于 2019-12-12 03:25:47

问题


I am searching for a command, that separates all given parameters with a specific delimiter, and outputs them quoted.

Example (delimiter is set to be a colon :):

somecommand "this is" "a" test

should output

"this is":"a":"test"

I'm aware that the shell interprets the "" quotes before passing the parameters to the command. So what the command should actually do is to print out every given parameter in quotes and separate all these with a colon.

I'm also not seeking for a bash-only solution, but for the most elegant solution.
It is very easy to just loop over an array of these elements and do that, but the problem is that I have to use this inside a gnu makefile which only allows single line shell commands and uses sh instead of bash.

So the simpler the better.


回答1:


How about

somecommand () {
    printf '"%s"\n' "$@" | paste -s -d :
}

Use printf to add the quotes and print every entry on a separate line, then use paste with the -s ("serial") option and a colon as the delimiter.

Can be called like this:

$ somecommand "this is" "a" test
"this is":"a":"test"



回答2:


As indicated in a number of the comments, a simple "loop-over" approach, looping over each of the strings passed as arguments is a fairly straight-forward way to approach it:

delimit_colon() {
    local first=1
    for i in "$@"; do
        if [ "$first" -eq 1 ]; then
            printf "%s" "$i"
            first=0
        else
            printf ":%s" "$i"
        fi
    done
    printf "\n"
}

Which when combined with a short test script could be:

#!/bin/bash

delimit_colon() {
    local first=1
    for i in "$@"; do
        if [ "$first" -eq 1 ]; then
            printf "%s" "$i"
            first=0
        else
            printf ":%s" "$i"
        fi
    done
    printf "\n"
}

[ -z "$1" ] && {  ## validate input
    printf "error: insufficient input\n"
    exit 1
}

delimit_colon "$@"

exit 0

Test Input/Output

$ bash delimitargs.sh "this is" "a" test
this is:a:test



回答3:


apply_delimiter () { 
    (( $# )) || return
    local res
    printf -v res '"%s":' "$@"
    printf '%s\n' "${res%:}"
}

Usage example:

$ apply_delimiter hello world "how are you"
"hello":"world":"how are you"



回答4:


Here a solution using the z-shell:

#!/usr/bin/zsh
# this is "somecommand"
echo '"'${(j_":"_)@}'"'



回答5:


If you have them in an array already, you can use this command

MYARRAY=("this is" "a" "test")
joined_string=$(IFS=:; echo "$(MYARRAY[*])")
echo $joined_string

Setting the IFS (internal field separator) will be the character separator. Using echo on the array will display the array using the newly set IFS. Putting those commands in $() will put the output of the echo into joined_string.



来源:https://stackoverflow.com/questions/34801908/bash-separate-parameters-with-specific-delimiter

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