tags:

views:

97

answers:

2

Hi,

I've known several operations we can do to variables in shell, e.g:

1) "#" & "##" operation

with ${var#pattern}, we remove "pattern" in the head of ${var}. "*" could be used in the pattern to match everything. And the difference between "#" and "##" is that, "##" will remove the longest match substring while "#" removes the shortest. For example,

var=brbread
${var##*br} // ead
${var#*br} // bread

2) "%" & "%%" operation

with ${var%pattern}, we remove "pattern" at the end of ${var}. Of course, "%%" indicates longest match while "%" means the shortest. For example,

var=eadbreadbread
${var%%*br} // eadbreadbread
${var%%br*} // ead
${var%br*} // eadbread

3) "/" operation

with ${var/haha/heihei}, we replace "haha" in $var with "heihei". For example,

var=ihahai
${var/haha/heihei/} / iheiheii

I'm just curious wether or not we can make more operations to variables other than above ones?

Thanks.

+3  A: 

Hi,

Yes there is a lot a other operations on variables with bash, as case modification, array keys listing, name expanding, etc.

You should check the manual page at the Parameter Expansion chapter.

Patrick MARIE
+3  A: 

In one of your examples, you could do a global replacement with two slashes:

${var//ha/hei/}  # the result would be the same

(Note that in Bash, the comment character is "#".)

Here are some examples of Parameter Expansion variable operations:

Provide a default:

$ unset foo
$ bar="hello"
$ echo ${foo:-$bar}    # if $foo had a value, it would be output
hello

Alternate value:

$ echo ${bar:+"goodbye"}
goodbye
$ echo ${foo:+"goodbye"}    # no substitution

Substrings:

$ echo ${bar:1:2}
el
$ echo ${bar: -4:2}    # from the end (note the space before the minus)
el

List of array keys:

$ array=(123 456)
$ array[12]=7890
$ echo ${!array[@]}
0 1 12

Parameter Length:

$ echo ${#bar}
5
$ echo ${#array[@]}    # number of elements in an array
3
$ echo ${#array[12]}   # length of an array element
4

Modify Case (Bash 4):

$ greeting="hello jim"
$ echo ${greeting^}
Hello jim
$ echo ${greeting^^}
HELLO JIM
$ greeting=($greeting)
$ echo ${greeting[@]^}
Hello Jim
Dennis Williamson