Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with bash with symbol

Tags:

string

bash

sed

awk

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

I need to get the test2 part of this string. How can I do this with bash?

like image 557
0xAX Avatar asked Aug 31 '25 00:08

0xAX


2 Answers

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.
like image 161
kojiro Avatar answered Sep 02 '25 23:09

kojiro


echo "test1@test2" | awk -F "@" '{print $2}'
like image 42
Debaditya Avatar answered Sep 02 '25 23:09

Debaditya