michael
michael

Reputation: 4483

Extract a piece of a string in bash?

I have following string in BASH and I need the email address at the end of the line

TAG instance    i-1846f265  AdminEmail  [email protected]

As far as I know the spacing between the words is always a single tab character, the email address at the end does not have a fixed length (could be one of any number of addresses)

Upvotes: 2

Views: 207

Answers (7)

Explosion Pills
Explosion Pills

Reputation: 191729

cut -f4 should work. If it's a file, cut -f4 file. If it's a string, cut -f <<<"$string"

Upvotes: 4

kojiro
kojiro

Reputation: 77089

You can read the string into an array and drop all the fields before the end:

read -a fields <<< 'TAG instance    i-1846f265  AdminEmail  [email protected]'
echo "${fields[@]: -1}"
[email protected]

If the tab delineation is important, you can set IFS=$'\t' before read to guarantee wordsplitting on tabs.

Upvotes: 0

Kent
Kent

Reputation: 195039

when I see "extract", I think of grep

grep -o '\S*$' file

Upvotes: 0

Atle
Atle

Reputation: 5447

If the column number is uncertain, making cut unreliable, you can do a regexp grep on something that looks like an email.

echo "TAG instance    i-1846f265  AdminEmail  [email protected]" | grep -o -e "[._a-zA-Z0-9-]\+*@[._a-zA-Z0-9-]\+"

Upvotes: 0

Vorsprung
Vorsprung

Reputation: 34307

If it is in a script then this (just bash, no external stuff) works

line='TAG instance    i-1846f265  AdminEmail  [email protected]'
set -- $line

echo "email address is " $5

There are numerous ways of splitting up a line like this. cut as mentioned, awk, sed

Upvotes: 3

Ofir Farchy
Ofir Farchy

Reputation: 8037

Have you tried:

echo $STRING | awk '{ print $NF }'

Or use cut as suggested above

Upvotes: -1

fedorqui
fedorqui

Reputation: 289555

You can use cut for this purpose:

$ cut   -f4                -d$'\t'                  your_file
         print 4th field    set tab as delimiter

Shorter:

$ cut -f4 -d$'\t' your_file

in case it is a string,

$ echo "your_strin" | cut -f4 -d$'\t' your_file

Upvotes: 2

Related Questions