Linux and Networking

Linux and Networking

4.24. Extraction of a substring.

To extract the substring from the pos position of the string str we will use the following command:

 

${str:pos}

 

Let’s see some examples of using this command:

 

$stringMY=ArrozConSocarrat

$echo ${stringMY:0}

ArrozConSocarrat

$echo ${stringMY:1}

rrozConSocarrat

$echo ${stringMY:7}

nSocarrat

 

As an exercise, we suggest that you execute the three commands in the previous code.

 

If what we want is to extract a certain number of characters from a specific position, we will use the following command:

 

${str:pos:len}

 

The above command extracts the substring from the pos position of the string str taking len characters.

 

Example:

 

$stringMY=ArrozConSocarrat

$echo ${stringMY:0:5}

Arroz

$echo ${stringMY:1:5}

rrozC

$echo ${stringMY:7:5}

nSoca

 

The following command would also work:

 

expr substr $string $position $length

 

Let’s see an example of using this command:

 

$stringMY=ArrozConSocarrat

$echo `expr substr $stringZ 4 3`

ozC

 

The Demeter Project