How to extract substring in Bash

https://‮ttual.www‬uri.com
How to extract substring in Bash

There are several ways to extract a substring in Bash. Here are a few options:

  1. Using the cut command:
cut -c start-index-inclusive-range-to-end-index-inclusive string

For example, to extract the substring abc from the string abcdef, you would run the following command:

cut -c1-3 abcdef

This will output abc.

  1. Using string expansion:
${string:start-index:length}

For example, to extract the substring abc from the string abcdef, you would run the following command:

echo "${abcdef:0:3}"

This will output abc.

  1. Using the sed command:
sed 's/.*\(substring-to-extract\).*/\1/' string

For example, to extract the substring abc from the string abcdef, you would run the following command:

echo "abcdef" | sed 's/.*\(abc\).*/\1/'

This will output abc.

Keep in mind that the cut, string expansion, and sed methods will only work if you know the exact substring you want to extract. If you want to extract a substring based on a pattern, you can use a tool like grep or awk.

Created Time:2017-10-16 14:38:45  Author:lautturi