Search This Blog

2009-05-28

Advance shell variable value substitution

Linux sh and bash support build-in value substitution within variable. It is equivalent to Windows command prompt feature as well

Following will show both MS-DOS and bash or sh in Linux

C:\>set c=3422

C:\>echo c=%c% new c=%c:4=558%
c=3422 new c=355822

C:\>echo c=%c% new c=%c:42=558%
c=3422 new c=35582

C:\>echo c=%c% new c=%c:2=55%
c=3422 new c=345555

UNIX bash shell equivalent:
$ a=3422
$ echo ${a/4/558}
355822
$ echo ${a/42/558}
35582
$ echo ${a//2/55}
345555
$ echo ${a/2/55}
34552

Example above show numeric, but it works for string. UNIX uses pattern matching, which is more powerful than MS-DOS

No comments: