Split string with bash with symbol

Using Parameter Expansion:

str='test1@test2'
echo "${str#*@}"
  1. The # character says Remove the smallest prefix of the expansion matching the pattern.
  2. The % character means Remove the smallest suffix of the expansion matching the pattern. (So you can do "${str%@*}" to get the "test1" part.)
  3. The / character means Remove the smallest and first substring of the expansion matching the following pattern. Bash has it, but it's not POSIX.

If you double the pattern character it matches greedily.

  1. ## means Remove the largest prefix of the expansion matching the pattern.
  2. %% means Remove the largest suffix of the expansion matching the pattern.
  3. // means Remove all substrings of the expansion matching the pattern.

echo "test1@test2" | awk -F "@" '{print $2}'

Another way in Bash:

IFS=@ read -r left right <<< "$string"
echo "$right"

Note that this technique also provides the first part of the string:

echo "$left"

Tags:

String

Bash

Awk

Sed