Monday, April 18, 2011

Split / Cut a String

Some people have trouble when cutting/split string in linux/unix. This article show some simple ways to cut/split string in shell:
Simple : use cut :
cut command only support cut strings with single character delemiter .
Advance: you can use ksh,perl,bash shell...
Example:
@string=blackcat.gatrong@gmail.com
and i want to cut tring gmail.com( to save blackcat.gatrong in somewhere...)
echo $string|cut -d'@' -f2

-d'@' : character dememiter is @
-f2 : cut part 2 ( here is gmail.com)

Example :
$str = "abc\@hotmail.com;xyz\@gmail.com;uvw\@yahoo.com";
I want to split to 3 individual email.

@arr = split(/;/, $str);
print "first: $arr[0]\n";
print "second: $arr[1]\n";
print "third: $arr[2]\n";


You can do the same thing with ksh :
#!/usr/bin/ksh

string="abc@hotmail.com;xyz@gmail.com;uvw@yahoo.com"

oIFS="$IFS"; IFS=';'
set -A str $string
IFS="$oIFS"

echo "strings count = ${#str[@]}"
echo "first : ${str[0]}";
echo "second: ${str[1]}";
echo "third : ${str[2]}";

With Bash shell :
string="abc@hotmail.com;xyz@gmail.com;uvw@yahoo.com"
var=$(echo $string | awk -F";" '{print $1,$2,$3}')
set -- $var
echo $1
echo $2
echo $3

No comments: