Extract a Substring in Bash Shell

This post will guide you how to extract a substring from a string in bash shell. How do I get a substring from a string using linux cut command. How to use the IFS to extract substring in Linux bash shell. How to use parameter expansion to extract a substring in bash.

Assuming that you defind a shell variable tmp, and set the value as a string “osetc.com“, and you want to extract the first 5 characters “osetc“. How to achieve it.

Extract a Substring Using IFS (Internal Field Separator)


The IFS internal variable is used to determine what characters Bash defines as word/item boundaries when processing character strings. By default set to whitespace characters of space, tab, and newline.

You need to set the IFS variable, and set its value as dot. so you can run the following commands:

# tmp="osetc.com"
# IFS=$'.'
# set -- $tmp
# echo $"$1"

Outputs:

[root@osetc ~]# tmp="osetc.com"
[root@osetc ~]# IFS=$'.'
[root@osetc ~]# set -- $tmp
[root@osetc ~]# echo "$1"
osetc

Extract a Substring Using Cut Tool


You can also use the cut command to extract a substring “osetc” from the tmp variable. just run the following command:

# echo $tmp | cut -d '.' -f 1

outputs:

[root@osetc ~]# echo $tmp | cut -d '.' -f 1
osetc

Extract a Substring Using Parameter Expansion


The parameter expansion expands to up to length characters of the value of parameter starting at the character specified by offset. The syntax is as below:

${parameter:offset:length}

To extract a substring “osetc” from a string variable “tmp”, you can execute the following parameter expansion:

#v="${tmp:0:5}"
# echo $v

outputs:

[root@osetc ~]# v="${tmp:0:5}"
[root@osetc ~]# echo $v
osetc

Note: If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.

You might also like:

Sidebar



back to top