Extracting substrings

Extracting substrings

How to:

Here’s the lowdown on substring extraction in Bash:

# Using ${string:start:length}
text="The quick brown fox"
echo $substring  # Outputs 'quick'

# Default length is rest of the string
echo $substring  # Outputs 'fox'

# Negative start index (from the end of the string)
substring=${text: -3}
echo $substring  # Outputs 'fox'

Deep Dive

Bash has handled strings since way back. Extracting substrings is an old-school trick, but still super handy. Before fancy tools, we just had parameter expansion – the ${} syntax – and it’s stood the test of time.

Alternatives? Sure. awk, cut, and grep can all slice and dice strings in their own way. But for a quick, no-extra-spawn job, Bash’s built-in method is efficient.

Implementation-wise, Bash grabs substrings without fuss. It doesn’t care what’s inside your string: text, numbers, unicorn emojis – whatever. Just give it the start and end, and it’ll blindly snip that piece out.

See Also

Dive deeper and check out these links: