Split string using bash with character

For example, I have a string: test1@test2.

I need to get part of test2this line. How to do this with bash?

+5
source share
4 answers

Using Extension Parameters :

str='test1@test2'
echo "${str#*@}"
  • The symbol #says: Remove the smallest extension prefix matching the pattern.
  • The symbol %means the removal of the smallest suffix of the extension corresponding to the pattern. (So ​​you can do "${str%@*}"to get the part "test1".)
  • The symbol /deletes the smallest and first expansion substring corresponding to the following pattern. Bash has it, but it is not POSIX.

, .

  • ## , .
  • %% , .
  • // , .
+19
echo "test1@test2" | awk -F "@" '{print $2}'
+9

Another way in bash:

IFS=@ read left right <<< "$string"
echo "$right"
+5
source
echo "test1@test2" | sed 's/.*@//'
+3
source

All Articles