views:

3903

answers:

5

I want to find a linux command that can return a part of the string. In most programming languages, it's the substr() function. Does bash have any command that can be used for this purpose. I want to be able to do something like this... substr "abcdefg" 2 3 - prints 'cde'


Subsequent similar question:

+21  A: 

From the bash manpage:

${parameter:offset}
${parameter:offset:length}
        Substring  Expansion.   Expands  to  up  to length characters of
        parameter starting at the character  specified  by  offset.


Or, if you are not sure of having bash, consider using cut.

dmckee
interesting, I did not know about this. For more flexibile substring options: man cut
Evan Teran
Shell extensions are nice, but... meh.
clintp
I mostly agree. I usually write shell scripts in vanilla /bin/sh. But I find that I have to know some bashisms to _read_ shell scripts...
dmckee
+3  A: 

In bash you can try this:

stringZ=abcABC123ABCabc
#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

Juanma
+1  A: 
${string:position:length}
Bill the Lizard
+7  A: 

If you are looking for a shell utility to do something like that, you can use the cut command.

To take your example, try:

echo "abcdefg" | cut -c3-5

Where -cN-M tells the cut command to return columns N to M, inclusive.

Toybuilder
+2  A: 

expr(1) has a substr subcommand:

expr substr string position length

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

camh