Find the answer to your Linux question:
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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just 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

    Code:
    import re
    a="Hello    world     111  222   .jpg"
    b=re.split('\s+',a)[2]    #Now I get b='111'
    But how can I do this using bash?

    Thanks for any suggestion~

  2. #2
    Just 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.

  3. #3
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,307
    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.

  4. #4
    Just Joined!
    Join Date
    Oct 2011
    Posts
    2
    Quote Originally Posted by atreyu View Post
    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.
    wow, this method seems much more clear and direct, thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •