Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash parameter expansion delimiter

I'm trying to get 1:2:3:4:5:6:7:8:9:10 using parameter expansion {1..10} and pattern matching:

$ var=$(echo {1..10})
$ echo ${var// /:}
1:2:3:4:5:6:7:8:9:10

Is there a more elegant way (one-liner) to do this?

like image 631
Yang Avatar asked May 23 '13 17:05

Yang


People also ask

What is bash parameter expansion?

Bash uses the value formed by expanding the rest of parameter as the new parameter ; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter . This is known as indirect expansion .

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

What does ${ parameter :- value Substitution operator does?

${var/Pattern/Replacement}First match of Pattern, within var replaced with Replacement. If Replacement is omitted, then the first match of Pattern is replaced by nothing, that is, deleted.

What is parameter substitution?

Manipulating and/or expanding variables ${parameter} Same as $parameter, i.e., value of the variable parameter. In certain contexts, only the less ambiguous ${parameter} form works. May be used for concatenating variables with strings.


2 Answers

Elegance is in the eye of the beholder:

( set {1..10} ; IFS=: ; echo "$*" )
like image 156
choroba Avatar answered Oct 26 '22 06:10

choroba


Agreeing with @choroba's comment about elegance, here are some other beholdables:

# seq is a gnu core utility
seq 1 10 | paste -sd:
# Or:
seq -s: 1 10

# {1..10} is bash-specific
printf "%d\n" {1..10} | paste -sd:

# posix compliant
yes | head -n10 | grep -n . | cut -d: -f1 | paste -sd:
like image 26
rici Avatar answered Oct 26 '22 04:10

rici