Results 1 to 4 of 4
Hi, I want to split a string and get specific parts using bash.
for example:
a="Hello world 111 222 .jpg"
Now I want to split a by space, and get ...
- 10-01-2011 #1Just Joined!
- Join Date
- Oct 2011
- Posts
- 2
split a string and index it using bash
Hi, I want to split a string and get specific parts using bash.
for example:
a="Hello world 111 222 .jpg"
Now I want to split a by space, and get the third substring.
I may do it in python as below
But how can I do this using bash?Code:import re a="Hello world 111 222 .jpg" b=re.split('\s+',a)[2] #Now I get b='111'
Thanks for any suggestion~
- 10-03-2011 #2Just Joined!
- Join Date
- Sep 2007
- Posts
- 4
How is going!? Well,, if you only need bash and theres just one space to split, so you could this:
a="Hello world 111 222 .jpg"
[users@locahost~]$ echo $a|cut -d' ' -f3
111
But, if theres one more space, we need awk like this:
[users@locahost ~]$ echo "$a"|awk -F' ' '{print $2}'
111
This it's better when theres no patter of number of the spaces between into the string we want to split.
Good luck.
- 10-03-2011 #3Linux Guru
- Join Date
- May 2011
- Posts
- 1,843
In Bash, I like to use arrays for this, e.g.:
Code:declare -a myarr myarr=($a) echo "Array: ${myarr[*]}" echo "number of elements: ${#myarr[*]}" echo "first element: ${myarr[0]}" echo "second element: ${myarr[1]" # etc.
- 10-04-2011 #4Just Joined!
- Join Date
- Oct 2011
- Posts
- 2


Reply With Quote
